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.
- package/LICENSE +21 -0
- package/README.md +99 -2
- package/dist/audit/index.d.ts +59 -0
- package/dist/audit/index.js +96 -0
- package/dist/cli/bin.d.ts +2 -0
- package/dist/cli/bin.js +11 -0
- package/dist/cli/cli.d.ts +10 -0
- package/dist/cli/cli.js +164 -0
- package/dist/cli/config.d.ts +18 -0
- package/dist/cli/config.js +49 -0
- package/dist/cli/errors.d.ts +16 -0
- package/dist/cli/errors.js +23 -0
- package/dist/cli/generate/generate.d.ts +33 -0
- package/dist/cli/generate/generate.js +84 -0
- package/dist/cli/generate/render.d.ts +23 -0
- package/dist/cli/generate/render.js +249 -0
- package/dist/cli/index.d.ts +12 -0
- package/dist/cli/index.js +12 -0
- package/dist/cli/init.d.ts +2 -0
- package/dist/cli/init.js +65 -0
- package/dist/cli/inspect.d.ts +10 -0
- package/dist/cli/inspect.js +82 -0
- package/dist/cli/packages.d.ts +6 -0
- package/dist/cli/packages.js +6 -0
- package/dist/cli/project.d.ts +18 -0
- package/dist/cli/project.js +39 -0
- package/dist/cli/resolve.d.ts +2 -0
- package/dist/cli/resolve.js +28 -0
- package/dist/core/compute/graph.d.ts +52 -0
- package/dist/core/compute/graph.js +162 -0
- package/dist/core/data/data.d.ts +59 -0
- package/dist/core/data/data.js +119 -0
- package/dist/core/data/load.d.ts +37 -0
- package/dist/core/data/load.js +236 -0
- package/dist/core/env/env.d.ts +468 -0
- package/dist/core/env/env.js +916 -0
- package/dist/core/env/identity.d.ts +43 -0
- package/dist/core/env/identity.js +65 -0
- package/dist/core/env/inspector.d.ts +55 -0
- package/dist/core/env/inspector.js +85 -0
- package/dist/core/env/time.d.ts +12 -0
- package/dist/core/env/time.js +38 -0
- package/dist/core/errors.d.ts +256 -0
- package/dist/core/errors.js +360 -0
- package/dist/core/events/events.d.ts +44 -0
- package/dist/core/events/events.js +58 -0
- package/dist/core/events/workers.d.ts +56 -0
- package/dist/core/events/workers.js +155 -0
- package/dist/core/index.d.ts +51 -0
- package/dist/core/index.js +42 -0
- package/dist/core/model/company.d.ts +6 -0
- package/dist/core/model/company.js +31 -0
- package/dist/core/model/faces.d.ts +42 -0
- package/dist/core/model/faces.js +1 -0
- package/dist/core/model/field.d.ts +479 -0
- package/dist/core/model/field.js +461 -0
- package/dist/core/model/generated.d.ts +77 -0
- package/dist/core/model/generated.js +1 -0
- package/dist/core/model/id.d.ts +33 -0
- package/dist/core/model/id.js +4 -0
- package/dist/core/model/model.d.ts +387 -0
- package/dist/core/model/model.js +566 -0
- package/dist/core/model/partition.d.ts +31 -0
- package/dist/core/model/partition.js +71 -0
- package/dist/core/model/related.d.ts +17 -0
- package/dist/core/model/related.js +60 -0
- package/dist/core/model/typed.d.ts +107 -0
- package/dist/core/model/typed.js +46 -0
- package/dist/core/money/currency.d.ts +39 -0
- package/dist/core/money/currency.js +37 -0
- package/dist/core/money/decimal.d.ts +26 -0
- package/dist/core/money/decimal.js +51 -0
- package/dist/core/money/fx.d.ts +68 -0
- package/dist/core/money/fx.js +124 -0
- package/dist/core/money/money.d.ts +84 -0
- package/dist/core/money/money.js +173 -0
- package/dist/core/money/quantity.d.ts +67 -0
- package/dist/core/money/quantity.js +108 -0
- package/dist/core/money/rounding.d.ts +11 -0
- package/dist/core/money/rounding.js +12 -0
- package/dist/core/recordset/aggregate.d.ts +22 -0
- package/dist/core/recordset/aggregate.js +258 -0
- package/dist/core/recordset/audit.d.ts +33 -0
- package/dist/core/recordset/audit.js +262 -0
- package/dist/core/recordset/compute.d.ts +36 -0
- package/dist/core/recordset/compute.js +414 -0
- package/dist/core/recordset/constraints.d.ts +9 -0
- package/dist/core/recordset/constraints.js +61 -0
- package/dist/core/recordset/domain.d.ts +31 -0
- package/dist/core/recordset/domain.js +300 -0
- package/dist/core/recordset/onchange.d.ts +43 -0
- package/dist/core/recordset/onchange.js +240 -0
- package/dist/core/recordset/recordset.d.ts +110 -0
- package/dist/core/recordset/recordset.js +789 -0
- package/dist/core/recordset/relations.d.ts +15 -0
- package/dist/core/recordset/relations.js +13 -0
- package/dist/core/recordset/rls.d.ts +15 -0
- package/dist/core/recordset/rls.js +108 -0
- package/dist/core/recordset/security.d.ts +56 -0
- package/dist/core/recordset/security.js +269 -0
- package/dist/core/recordset/sequences.d.ts +31 -0
- package/dist/core/recordset/sequences.js +154 -0
- package/dist/core/recordset/source.d.ts +9 -0
- package/dist/core/recordset/source.js +19 -0
- package/dist/core/recordset/sqlErrors.d.ts +6 -0
- package/dist/core/recordset/sqlErrors.js +39 -0
- package/dist/core/recordset/transitions.d.ts +10 -0
- package/dist/core/recordset/transitions.js +80 -0
- package/dist/core/recordset/types.d.ts +415 -0
- package/dist/core/recordset/types.js +8 -0
- package/dist/core/recordset/values.d.ts +33 -0
- package/dist/core/recordset/values.js +177 -0
- package/dist/core/recordset/writes.d.ts +42 -0
- package/dist/core/recordset/writes.js +786 -0
- package/dist/core/registry/ddl.d.ts +31 -0
- package/dist/core/registry/ddl.js +174 -0
- package/dist/core/registry/extension.d.ts +94 -0
- package/dist/core/registry/extension.js +90 -0
- package/dist/core/registry/module.d.ts +89 -0
- package/dist/core/registry/module.js +98 -0
- package/dist/core/registry/registry.d.ts +130 -0
- package/dist/core/registry/registry.js +591 -0
- package/dist/core/security/runtime.d.ts +102 -0
- package/dist/core/security/runtime.js +232 -0
- package/dist/driver-pg/driver.d.ts +88 -0
- package/dist/driver-pg/driver.js +177 -0
- package/dist/driver-pg/errors.d.ts +72 -0
- package/dist/driver-pg/errors.js +182 -0
- package/dist/driver-pg/index.d.ts +7 -0
- package/dist/driver-pg/index.js +7 -0
- package/dist/i18n/index.d.ts +25 -0
- package/dist/i18n/index.js +51 -0
- package/dist/migrate/apply.d.ts +78 -0
- package/dist/migrate/apply.js +167 -0
- package/dist/migrate/catalog.d.ts +10 -0
- package/dist/migrate/catalog.js +122 -0
- package/dist/migrate/diff.d.ts +98 -0
- package/dist/migrate/diff.js +160 -0
- package/dist/migrate/errors.d.ts +21 -0
- package/dist/migrate/errors.js +31 -0
- package/dist/migrate/index.d.ts +18 -0
- package/dist/migrate/index.js +18 -0
- package/dist/migrate/render.d.ts +5 -0
- package/dist/migrate/render.js +101 -0
- package/dist/migrate/schema.d.ts +61 -0
- package/dist/migrate/schema.js +233 -0
- package/dist/security/index.d.ts +147 -0
- package/dist/security/index.js +278 -0
- package/dist/sequence/index.d.ts +63 -0
- package/dist/sequence/index.js +106 -0
- package/dist/sql/ast.d.ts +49 -0
- package/dist/sql/ast.js +47 -0
- package/dist/sql/builder/builder.d.ts +215 -0
- package/dist/sql/builder/builder.js +308 -0
- package/dist/sql/builder/expression.d.ts +80 -0
- package/dist/sql/builder/expression.js +126 -0
- package/dist/sql/compile.d.ts +18 -0
- package/dist/sql/compile.js +41 -0
- package/dist/sql/errors.d.ts +13 -0
- package/dist/sql/errors.js +16 -0
- package/dist/sql/index.d.ts +19 -0
- package/dist/sql/index.js +19 -0
- package/dist/sql/tag.d.ts +47 -0
- package/dist/sql/tag.js +123 -0
- package/package.json +82 -4
|
@@ -0,0 +1,591 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `buildRegistry()` (RFC 0002 §7.4): loads modules in dependency order, applies extensions under the view-safety
|
|
3
|
+
* rules, composes method chains, and runs the cross-model checks. The registry's type is the schema view of every
|
|
4
|
+
* model (with its extensions) in the module tree.
|
|
5
|
+
*/
|
|
6
|
+
import { DuplicateModelError, DuplicateModuleError, ExtensionConflictError, InvalidDependsPathError, InvalidExtensionError, InvalidModuleError, InvalidRelationError, UndeclaredDependencyError, UnknownModelError, UnknownSequenceError, } from '../errors.js';
|
|
7
|
+
import { overrideField, } from '../model/field.js';
|
|
8
|
+
import { defineModel, markTransition, RESERVED_KEYS, transitionOf, } from '../model/model.js';
|
|
9
|
+
import { isModule } from './module.js';
|
|
10
|
+
// ------------------------------------------------------------------------------------------------- schema types
|
|
11
|
+
import { groupClosure, mergeAccess, normalizeFieldGroups, SecurityDefinitionError, } from '../../security/index.js';
|
|
12
|
+
import { buildComputeGraph } from '../compute/graph.js';
|
|
13
|
+
import { validateData } from '../data/data.js';
|
|
14
|
+
import { delegatedField } from '../model/field.js';
|
|
15
|
+
import { relatedPath } from '../model/related.js';
|
|
16
|
+
const RELATION_KINDS = new Set(['many2one', 'one2many', 'many2many']);
|
|
17
|
+
/** The target model of a relation field, else `undefined`. */
|
|
18
|
+
export function targetOf(field) {
|
|
19
|
+
return RELATION_KINDS.has(field.kind)
|
|
20
|
+
? field.target
|
|
21
|
+
: undefined;
|
|
22
|
+
}
|
|
23
|
+
// ----------------------------------------------------------------------------------------------------- loading
|
|
24
|
+
/** Collects every module reachable from the roots and checks that names are unique. */
|
|
25
|
+
function collect(roots) {
|
|
26
|
+
const byName = new Map();
|
|
27
|
+
const visit = (module) => {
|
|
28
|
+
if (!isModule(module))
|
|
29
|
+
throw new DuplicateModuleError(String(module.name ?? '?'));
|
|
30
|
+
const known = byName.get(module.name);
|
|
31
|
+
if (known === module)
|
|
32
|
+
return;
|
|
33
|
+
if (known !== undefined)
|
|
34
|
+
throw new DuplicateModuleError(module.name);
|
|
35
|
+
byName.set(module.name, module);
|
|
36
|
+
for (const dep of module.depends)
|
|
37
|
+
visit(dep);
|
|
38
|
+
};
|
|
39
|
+
for (const root of roots)
|
|
40
|
+
visit(root);
|
|
41
|
+
return byName;
|
|
42
|
+
}
|
|
43
|
+
/** Kahn's algorithm with the smallest name first: the order is a pure function of the module set (RFC 0002 R5). */
|
|
44
|
+
function order(byName) {
|
|
45
|
+
const remaining = new Map();
|
|
46
|
+
for (const [name, module] of byName)
|
|
47
|
+
remaining.set(name, new Set(module.depends.map((d) => d.name)));
|
|
48
|
+
const result = [];
|
|
49
|
+
while (remaining.size > 0) {
|
|
50
|
+
const ready = [...remaining.entries()]
|
|
51
|
+
.filter(([, deps]) => deps.size === 0)
|
|
52
|
+
.map(([name]) => name)
|
|
53
|
+
.sort();
|
|
54
|
+
const next = ready[0];
|
|
55
|
+
if (next === undefined) {
|
|
56
|
+
// Unreachable with module objects (a module can't depend on one defined after it), kept as a guard.
|
|
57
|
+
throw new DuplicateModuleError([...remaining.keys()].join(' → '));
|
|
58
|
+
}
|
|
59
|
+
const module = byName.get(next);
|
|
60
|
+
if (module !== undefined)
|
|
61
|
+
result.push(module);
|
|
62
|
+
remaining.delete(next);
|
|
63
|
+
for (const deps of remaining.values())
|
|
64
|
+
deps.delete(next);
|
|
65
|
+
}
|
|
66
|
+
return result;
|
|
67
|
+
}
|
|
68
|
+
/** Transitive dependency names of a module, including itself. */
|
|
69
|
+
function closure(module) {
|
|
70
|
+
const names = new Set();
|
|
71
|
+
const walk = (m) => {
|
|
72
|
+
if (names.has(m.name))
|
|
73
|
+
return;
|
|
74
|
+
names.add(m.name);
|
|
75
|
+
for (const dep of m.depends)
|
|
76
|
+
walk(dep);
|
|
77
|
+
};
|
|
78
|
+
walk(module);
|
|
79
|
+
return names;
|
|
80
|
+
}
|
|
81
|
+
function draftOf(model, module) {
|
|
82
|
+
const fieldOrigins = {};
|
|
83
|
+
for (const key of Object.keys(model.fields))
|
|
84
|
+
fieldOrigins[key] = module;
|
|
85
|
+
const methodLayers = {};
|
|
86
|
+
for (const key of Object.keys(model.methods))
|
|
87
|
+
methodLayers[key] = [{ module, kind: 'definition' }];
|
|
88
|
+
const def = model.definition;
|
|
89
|
+
return {
|
|
90
|
+
base: model,
|
|
91
|
+
module,
|
|
92
|
+
extensions: [],
|
|
93
|
+
fields: { ...def.fields },
|
|
94
|
+
fieldOrigins,
|
|
95
|
+
methods: { ...model.methods },
|
|
96
|
+
methodLayers,
|
|
97
|
+
constraints: { ...(def.constraints ?? {}) },
|
|
98
|
+
onchange: { ...(def.onchange ?? {}) },
|
|
99
|
+
access: { ...(def.access ?? {}) },
|
|
100
|
+
rules: { ...(def.rules ?? {}) },
|
|
101
|
+
sqlConstraints: { ...(def.sqlConstraints ?? {}) },
|
|
102
|
+
indexes: [...(def.indexes ?? [])],
|
|
103
|
+
tracking: [...(def.tracking ?? [])],
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/** Wraps `prev` with `layer`: `layer.call(this, next, ...args)` where `next` is `prev` bound to `this`. */
|
|
107
|
+
function compose(prev, layer) {
|
|
108
|
+
const composed = function composed(...args) {
|
|
109
|
+
const next = (...nextArgs) => prev.apply(this, nextArgs);
|
|
110
|
+
return layer.call(this, next, ...args);
|
|
111
|
+
};
|
|
112
|
+
// A wrapped transition is still the transition (the rebuilt model must not regenerate it, RFC 0010 §7.1).
|
|
113
|
+
const transition = transitionOf(prev);
|
|
114
|
+
return transition === undefined
|
|
115
|
+
? composed
|
|
116
|
+
: markTransition(composed, transition.field, transition.name);
|
|
117
|
+
}
|
|
118
|
+
function applyExtension(draft, ext, module, reachable) {
|
|
119
|
+
const where = `Module '${module}' extending '${ext.name}'`;
|
|
120
|
+
const conflict = (what, key, origin, fix) => {
|
|
121
|
+
const problem = reachable.has(origin)
|
|
122
|
+
? `${where}: ${what} '${key}' already exists (from '${origin}').`
|
|
123
|
+
: `${what} '${key}' of '${ext.name}' is added by both '${origin}' and '${module}', which do not depend on each other.`;
|
|
124
|
+
throw new ExtensionConflictError(problem, fix);
|
|
125
|
+
};
|
|
126
|
+
for (const [key, field] of Object.entries(ext.fields)) {
|
|
127
|
+
const origin = draft.fieldOrigins[key];
|
|
128
|
+
if (origin !== undefined) {
|
|
129
|
+
conflict('field', key, origin, reachable.has(origin)
|
|
130
|
+
? 'Use fieldOverrides to change an existing field.'
|
|
131
|
+
: 'Rename one field, or make one module depend on the other and use fieldOverrides.');
|
|
132
|
+
}
|
|
133
|
+
if (field.required &&
|
|
134
|
+
field.default === undefined &&
|
|
135
|
+
!field.computed &&
|
|
136
|
+
field.kind !== 'boolean' &&
|
|
137
|
+
// x2many relations are "required" only in the sense that they always hold a (possibly empty) list.
|
|
138
|
+
field.kind !== 'one2many' &&
|
|
139
|
+
field.kind !== 'many2many') {
|
|
140
|
+
throw new InvalidExtensionError(`${where}: the new field '${key}' is required but has no default.`, 'A required field added by an extension needs a default or a compute (RFC 0002 S1), so code that does not know the field can still create records.');
|
|
141
|
+
}
|
|
142
|
+
draft.fields[key] = field;
|
|
143
|
+
draft.fieldOrigins[key] = module;
|
|
144
|
+
}
|
|
145
|
+
for (const [key, override] of Object.entries(ext.fieldOverrides)) {
|
|
146
|
+
const field = draft.fields[key];
|
|
147
|
+
if (field === undefined) {
|
|
148
|
+
const implicit = draft.base.fields[key] !== undefined;
|
|
149
|
+
throw new InvalidExtensionError(`${where}: fieldOverrides names '${key}', which is ${implicit ? 'an implicit field' : 'not a field'} of '${ext.name}'.`, implicit
|
|
150
|
+
? 'Implicit fields (id, createdAt, company, ...) cannot be overridden.'
|
|
151
|
+
: `Fields: ${Object.keys(draft.fields).join(', ')}.`);
|
|
152
|
+
}
|
|
153
|
+
const changes = {};
|
|
154
|
+
for (const [attr, value] of Object.entries(override)) {
|
|
155
|
+
if (value === undefined)
|
|
156
|
+
continue;
|
|
157
|
+
switch (attr) {
|
|
158
|
+
case 'label':
|
|
159
|
+
case 'help':
|
|
160
|
+
case 'default':
|
|
161
|
+
case 'index':
|
|
162
|
+
case 'tracking':
|
|
163
|
+
case 'copy':
|
|
164
|
+
Object.assign(changes, { [attr]: value });
|
|
165
|
+
break;
|
|
166
|
+
case 'groups':
|
|
167
|
+
Object.assign(changes, { groups: normalizeFieldGroups(value) });
|
|
168
|
+
break;
|
|
169
|
+
case 'required': {
|
|
170
|
+
if (value === false && field.required) {
|
|
171
|
+
throw new InvalidExtensionError(`${where}: fieldOverrides.${key} relaxes required to false.`, 'Required can only be tightened (RFC 0002 S2): code compiled against the original view reads a non-null value.');
|
|
172
|
+
}
|
|
173
|
+
if (value === true &&
|
|
174
|
+
!field.required &&
|
|
175
|
+
override.default === undefined &&
|
|
176
|
+
field.default === undefined) {
|
|
177
|
+
throw new InvalidExtensionError(`${where}: fieldOverrides.${key} sets required without a default.`, 'Give the field a default in the same override (RFC 0002 S2), so existing create() calls keep working.');
|
|
178
|
+
}
|
|
179
|
+
Object.assign(changes, { required: value });
|
|
180
|
+
break;
|
|
181
|
+
}
|
|
182
|
+
case 'selectionAdd': {
|
|
183
|
+
const selectable = field;
|
|
184
|
+
if ((field.kind !== 'selection' && field.kind !== 'state') ||
|
|
185
|
+
typeof selectable.selection === 'function') {
|
|
186
|
+
throw new InvalidExtensionError(`${where}: fieldOverrides.${key}.selectionAdd on a ${field.kind} field.`, 'selectionAdd applies to selection and state fields with a static map.');
|
|
187
|
+
}
|
|
188
|
+
if (selectable.extensible !== true) {
|
|
189
|
+
throw new InvalidExtensionError(`${where}: '${key}' is not an extensible selection.`, 'The owner must declare the field with extensible: true (RFC 0002 S5); consumers then handle unknown values.');
|
|
190
|
+
}
|
|
191
|
+
const existing = selectable.selection ?? [];
|
|
192
|
+
const added = Object.entries(value).filter(([k]) => !existing.some(([e]) => e === k));
|
|
193
|
+
changes.selection = [...existing, ...added.map(([k, v]) => [k, v])];
|
|
194
|
+
break;
|
|
195
|
+
}
|
|
196
|
+
case 'statesAdd':
|
|
197
|
+
case 'transitionsAdd': {
|
|
198
|
+
const stateField = field;
|
|
199
|
+
if (field.kind !== 'state') {
|
|
200
|
+
throw new InvalidExtensionError(`${where}: fieldOverrides.${key}.${attr} on a ${field.kind} field.`, 'statesAdd / transitionsAdd apply to state fields.');
|
|
201
|
+
}
|
|
202
|
+
if (stateField.extensible !== true) {
|
|
203
|
+
throw new InvalidExtensionError(`${where}: '${key}' is not an extensible state field.`, 'The owner must declare the field with extensible: true (RFC 0002 S6).');
|
|
204
|
+
}
|
|
205
|
+
const selection = [...(changes.selection ?? stateField.selection ?? [])];
|
|
206
|
+
const hooks = {
|
|
207
|
+
...(changes.stateHooks ?? stateField.stateHooks ?? {}),
|
|
208
|
+
};
|
|
209
|
+
const transitions = {
|
|
210
|
+
...(changes.transitions ?? stateField.transitions ?? {}),
|
|
211
|
+
};
|
|
212
|
+
if (attr === 'statesAdd') {
|
|
213
|
+
for (const [s, spec] of Object.entries(value)) {
|
|
214
|
+
if (selection.some(([e]) => e === s))
|
|
215
|
+
throw new InvalidExtensionError(`${where}: state '${s}' already exists on '${key}'.`, 'Add new states only (RFC 0002 S6).');
|
|
216
|
+
selection.push([s, typeof spec === 'string' ? spec : spec.label]);
|
|
217
|
+
if (typeof spec !== 'string' &&
|
|
218
|
+
(spec.onEnter !== undefined || spec.onExit !== undefined))
|
|
219
|
+
hooks[s] = {
|
|
220
|
+
...(spec.onEnter === undefined ? {} : { onEnter: spec.onEnter }),
|
|
221
|
+
...(spec.onExit === undefined ? {} : { onExit: spec.onExit }),
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
Object.assign(changes, { selection, stateHooks: hooks });
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
const states = new Set(selection.map(([s]) => s));
|
|
228
|
+
for (const [tname, t] of Object.entries(value)) {
|
|
229
|
+
if (transitions[tname] !== undefined)
|
|
230
|
+
throw new InvalidExtensionError(`${where}: transition '${tname}' already exists on '${key}'.`, 'Add new transitions only; wrap existing ones with overrides (RFC 0002 S6).');
|
|
231
|
+
for (const s of [...t.from, t.to]) {
|
|
232
|
+
if (!states.has(s))
|
|
233
|
+
throw new InvalidExtensionError(`${where}: transition '${tname}' refers to unknown state '${s}'.`, `States of '${key}': ${[...states].join(', ')} (add states with statesAdd first, in the same override).`);
|
|
234
|
+
}
|
|
235
|
+
transitions[tname] = t;
|
|
236
|
+
draft.methodLayers[tname] = [{ module, kind: 'definition' }];
|
|
237
|
+
}
|
|
238
|
+
Object.assign(changes, { transitions });
|
|
239
|
+
}
|
|
240
|
+
break;
|
|
241
|
+
}
|
|
242
|
+
default:
|
|
243
|
+
throw new InvalidExtensionError(`${where}: fieldOverrides.${key}.${attr} is not an attribute an extension may change.`, 'Allowed: label, help, default, index, tracking, copy, groups, required (tighten only), selectionAdd, statesAdd, transitionsAdd (RFC 0002 S2–S6).');
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
draft.fields[key] = overrideField(field, changes);
|
|
247
|
+
}
|
|
248
|
+
for (const [key, fn] of Object.entries(ext.methods)) {
|
|
249
|
+
const layers = draft.methodLayers[key];
|
|
250
|
+
if (layers !== undefined) {
|
|
251
|
+
const origin = layers[0]?.module ?? draft.module;
|
|
252
|
+
conflict('method', key, origin, reachable.has(origin)
|
|
253
|
+
? 'Use overrides to wrap an existing method.'
|
|
254
|
+
: 'Rename one method, or make one module depend on the other and use overrides.');
|
|
255
|
+
}
|
|
256
|
+
draft.methods[key] = fn;
|
|
257
|
+
draft.methodLayers[key] = [{ module, kind: 'definition' }];
|
|
258
|
+
}
|
|
259
|
+
for (const [key, { kind, fn }] of Object.entries(ext.overrides)) {
|
|
260
|
+
const prev = draft.methods[key];
|
|
261
|
+
if (prev === undefined) {
|
|
262
|
+
throw new InvalidExtensionError(`${where}: overrides names '${key}', which is not a method of '${ext.name}'.`, `Methods: ${Object.keys(draft.methods).join(', ') || '(none)'}. Add new methods under \`methods\`.`);
|
|
263
|
+
}
|
|
264
|
+
draft.methods[key] = kind === 'replace' ? fn : compose(prev, fn);
|
|
265
|
+
draft.methodLayers[key] = [...(draft.methodLayers[key] ?? []), { module, kind }];
|
|
266
|
+
}
|
|
267
|
+
for (const [key, spec] of Object.entries(ext.constraints)) {
|
|
268
|
+
if (draft.constraints[key] !== undefined)
|
|
269
|
+
conflict('constraint', key, draft.module, 'Use a different constraint key.');
|
|
270
|
+
draft.constraints[key] = spec;
|
|
271
|
+
}
|
|
272
|
+
draft.access = mergeAccess(draft.access, ext.access);
|
|
273
|
+
for (const [key, rule] of Object.entries(ext.rules)) {
|
|
274
|
+
if (draft.rules[key] !== undefined)
|
|
275
|
+
conflict('rule', key, draft.module, 'Use a different rule key.');
|
|
276
|
+
draft.rules[key] = rule;
|
|
277
|
+
}
|
|
278
|
+
for (const [key, fn] of Object.entries(ext.onchange)) {
|
|
279
|
+
if (draft.onchange[key] !== undefined)
|
|
280
|
+
conflict('onchange', key, draft.module, 'Call a shared method from the existing handler instead.');
|
|
281
|
+
draft.onchange[key] = fn;
|
|
282
|
+
}
|
|
283
|
+
for (const [key, spec] of Object.entries(ext.sqlConstraints)) {
|
|
284
|
+
if (draft.sqlConstraints[key] !== undefined)
|
|
285
|
+
conflict('sqlConstraints', key, draft.module, 'Use a different key (prefix it with the module name).');
|
|
286
|
+
draft.sqlConstraints[key] = spec;
|
|
287
|
+
}
|
|
288
|
+
draft.indexes.push(...ext.indexes);
|
|
289
|
+
for (const key of ext.tracking)
|
|
290
|
+
if (!draft.tracking.includes(key))
|
|
291
|
+
draft.tracking.push(key);
|
|
292
|
+
draft.extensions.push(module);
|
|
293
|
+
}
|
|
294
|
+
/** Rebuilds the final model from the draft through `defineModel`, so every model-level check applies to it. */
|
|
295
|
+
function finalize(draft) {
|
|
296
|
+
const def = draft.base.definition;
|
|
297
|
+
const model = defineModel(draft.base.name, {
|
|
298
|
+
...def,
|
|
299
|
+
fields: draft.fields,
|
|
300
|
+
methods: draft.methods,
|
|
301
|
+
constraints: draft.constraints,
|
|
302
|
+
onchange: draft.onchange,
|
|
303
|
+
access: draft.access,
|
|
304
|
+
rules: draft.rules,
|
|
305
|
+
sqlConstraints: draft.sqlConstraints,
|
|
306
|
+
indexes: draft.indexes,
|
|
307
|
+
tracking: draft.tracking,
|
|
308
|
+
});
|
|
309
|
+
const fieldOrigins = {};
|
|
310
|
+
for (const key of Object.keys(model.fields))
|
|
311
|
+
fieldOrigins[key] = draft.fieldOrigins[key] ?? draft.module;
|
|
312
|
+
return {
|
|
313
|
+
model,
|
|
314
|
+
module: draft.module,
|
|
315
|
+
extensions: Object.freeze([...draft.extensions]),
|
|
316
|
+
fieldOrigins: Object.freeze(fieldOrigins),
|
|
317
|
+
methodLayers: Object.freeze(Object.fromEntries(Object.entries(draft.methodLayers).map(([k, v]) => [k, Object.freeze([...v])]))),
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
// -------------------------------------------------------------------------------------------------- building
|
|
321
|
+
/**
|
|
322
|
+
* Builds the registry: collects and orders modules, registers models, applies extensions in load order under the
|
|
323
|
+
* view-safety rules, and runs the checks that need every model: relation targets exist and belong to a declared
|
|
324
|
+
* dependency, one2many inverses point back, `depends` paths resolve.
|
|
325
|
+
*
|
|
326
|
+
* @throws {DuplicateModuleError} {DuplicateModelError} {UnknownModelError} {UndeclaredDependencyError}
|
|
327
|
+
* {InvalidRelationError} {InvalidDependsPathError} {InvalidExtensionError} {ExtensionConflictError}
|
|
328
|
+
*/
|
|
329
|
+
export function buildRegistry(options) {
|
|
330
|
+
const modules = order(collect(options.modules));
|
|
331
|
+
const closures = new Map(modules.map((m) => [m.name, closure(m)]));
|
|
332
|
+
const drafts = new Map();
|
|
333
|
+
for (const module of modules) {
|
|
334
|
+
for (const model of module.models) {
|
|
335
|
+
const existing = drafts.get(model.name);
|
|
336
|
+
if (existing !== undefined)
|
|
337
|
+
throw new DuplicateModelError(model.name, [existing.module, module.name]);
|
|
338
|
+
drafts.set(model.name, draftOf(model, module.name));
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
for (const module of modules) {
|
|
342
|
+
const reachable = closures.get(module.name) ?? new Set();
|
|
343
|
+
for (const ext of module.extensions) {
|
|
344
|
+
const draft = drafts.get(ext.name);
|
|
345
|
+
if (draft === undefined)
|
|
346
|
+
throw new UnknownModelError(ext.name, `the extension in module '${module.name}'`);
|
|
347
|
+
if (!reachable.has(draft.module))
|
|
348
|
+
throw new UndeclaredDependencyError(module.name, ext.name, draft.module, 'an extension');
|
|
349
|
+
applyExtension(draft, ext, module.name, reachable);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
// Delegation: the parent's fields (after its extensions) become writable related fields of the child.
|
|
353
|
+
for (const draft of drafts.values()) {
|
|
354
|
+
for (const key of draft.base.definition.delegates ??
|
|
355
|
+
[]) {
|
|
356
|
+
const target = draft.fields[key]?.target ?? '';
|
|
357
|
+
const parent = drafts.get(target);
|
|
358
|
+
if (parent === undefined)
|
|
359
|
+
throw new UnknownModelError(target, `delegates '${key}' of '${draft.base.name}'`);
|
|
360
|
+
for (const [pk, pf] of Object.entries(parent.fields)) {
|
|
361
|
+
if (RESERVED_KEYS.includes(pk) || pk in draft.fields)
|
|
362
|
+
continue;
|
|
363
|
+
if (pf.kind === 'one2many' || pf.kind === 'many2many' || pf.kind === 'state')
|
|
364
|
+
continue;
|
|
365
|
+
draft.fields[pk] = delegatedField(pf, `${key}.${pk}`);
|
|
366
|
+
draft.fieldOrigins[pk] = parent.fieldOrigins[pk] ?? parent.module;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
const models = new Map();
|
|
371
|
+
for (const [name, draft] of drafts)
|
|
372
|
+
models.set(name, finalize(draft));
|
|
373
|
+
const resolve = (fromModule, target, via) => {
|
|
374
|
+
const found = models.get(target);
|
|
375
|
+
if (found === undefined)
|
|
376
|
+
throw new UnknownModelError(target, via);
|
|
377
|
+
if (!closures.get(fromModule)?.has(found.module))
|
|
378
|
+
throw new UndeclaredDependencyError(fromModule, target, found.module, via);
|
|
379
|
+
return found;
|
|
380
|
+
};
|
|
381
|
+
const securityGroups = new Map();
|
|
382
|
+
for (const module of modules) {
|
|
383
|
+
for (const group of module.groups) {
|
|
384
|
+
if (securityGroups.has(group.code)) {
|
|
385
|
+
throw new InvalidModuleError(`Module '${module.name}' declares the group '${group.code}', which another module already declares.`, 'Group codes are global: declare each group once.');
|
|
386
|
+
}
|
|
387
|
+
securityGroups.set(group.code, group);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
const permissions = new Map();
|
|
391
|
+
for (const module of modules) {
|
|
392
|
+
for (const permission of module.permissions) {
|
|
393
|
+
if (permissions.has(permission.code))
|
|
394
|
+
throw new InvalidModuleError(`Module '${module.name}' declares the permission '${permission.code}', which another module already declares.`, 'Permission codes are global: declare each permission once.');
|
|
395
|
+
for (const code of permission.groups)
|
|
396
|
+
if (!securityGroups.has(code))
|
|
397
|
+
throw new InvalidModuleError(`Permission '${permission.code}' is granted to the group '${code}', which no module declares.`, 'Declare it with defineGroup() in a module, or fix the code.');
|
|
398
|
+
permissions.set(permission.code, permission);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
for (const { model } of models.values()) {
|
|
402
|
+
for (const [key, field] of Object.entries(model.fields)) {
|
|
403
|
+
const transitions = field.transitions;
|
|
404
|
+
for (const [name, t] of Object.entries(transitions ?? {}))
|
|
405
|
+
if (t.requires !== undefined && !permissions.has(t.requires))
|
|
406
|
+
throw new InvalidModuleError(`Transition '${name}' of ${model.name}.${key} requires the permission '${t.requires}', which no module declares.`, 'Declare it with definePermission() in a module, or fix the code.');
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
for (const { model } of models.values()) {
|
|
410
|
+
if (model.backdate !== undefined && !permissions.has(model.backdate.permission))
|
|
411
|
+
throw new InvalidModuleError(`Model '${model.name}' requires the permission '${model.backdate.permission}' for back-dated entries, which no module declares.`, 'Declare it with definePermission() in a module, or fix the code.');
|
|
412
|
+
}
|
|
413
|
+
const administrators = new Set([...securityGroups.values()].filter((g) => g.administrator).map((g) => g.code));
|
|
414
|
+
for (const { model } of models.values()) {
|
|
415
|
+
for (const code of [
|
|
416
|
+
...Object.keys(model.access),
|
|
417
|
+
...Object.values(model.rules).flatMap((r) => (r.groups === 'global' ? [] : [...r.groups])),
|
|
418
|
+
]) {
|
|
419
|
+
if (!securityGroups.has(code))
|
|
420
|
+
throw new InvalidModuleError(`Model '${model.name}' grants access to the group '${code}', which no module declares.`, 'Declare it with defineGroup() in a module, or fix the code.');
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
const sequences = new Map();
|
|
424
|
+
for (const module of modules) {
|
|
425
|
+
for (const definition of module.sequences) {
|
|
426
|
+
if (sequences.has(definition.code)) {
|
|
427
|
+
throw new InvalidModuleError(`Module '${module.name}' declares the sequence '${definition.code}', which another module already declares.`, 'Sequence codes are global: prefix them with the module name, or declare the sequence once.');
|
|
428
|
+
}
|
|
429
|
+
sequences.set(definition.code, definition);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
for (const registered of models.values()) {
|
|
433
|
+
const { model } = registered;
|
|
434
|
+
for (const [key, field] of Object.entries(model.fields)) {
|
|
435
|
+
const where = `field '${key}' of model '${model.name}'`;
|
|
436
|
+
const fromModule = registered.fieldOrigins[key] ?? registered.module;
|
|
437
|
+
const target = targetOf(field);
|
|
438
|
+
if (target !== undefined) {
|
|
439
|
+
const other = resolve(fromModule, target, where);
|
|
440
|
+
const withoutKey = field.kind === 'many2one' && field.foreignKey === false;
|
|
441
|
+
if (field.kind !== 'one2many' && other.model.partition !== undefined && !withoutKey) {
|
|
442
|
+
throw new InvalidRelationError(`${where} points at '${target}', which is partitioned.`, 'A foreign key cannot reference a partitioned table without its partition key: use f.many2one(target, { foreignKey: false }) (ids checked by the ORM), or reference a non-partitioned model.');
|
|
443
|
+
}
|
|
444
|
+
if (field.kind === 'one2many') {
|
|
445
|
+
const inverseKey = field.inverseField;
|
|
446
|
+
const inverse = other.model.fields[inverseKey];
|
|
447
|
+
if (inverse === undefined ||
|
|
448
|
+
inverse.kind !== 'many2one' ||
|
|
449
|
+
targetOf(inverse) !== model.name) {
|
|
450
|
+
throw new InvalidRelationError(`The one2many ${where} names inverse '${inverseKey}', which is not a many2one('${model.name}') on '${target}'.`, `Declare ${inverseKey}: f.many2one('${model.name}') on '${target}', or point the one2many at the right inverse field.`);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
if (field.kind === 'many2one' &&
|
|
455
|
+
field.checkCompany === true) {
|
|
456
|
+
const targetName = targetOf(field) ?? '';
|
|
457
|
+
const targetModel = resolve(fromModule, targetName, where).model;
|
|
458
|
+
if (targetModel.companyScoped === undefined) {
|
|
459
|
+
throw new InvalidRelationError(`${where} has checkCompany, but '${targetName}' is not companyScoped.`, 'checkCompany compares the companies of both records: make the target companyScoped, or drop the option.');
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
for (const [kind, codes] of [
|
|
463
|
+
['read', field.groups.read],
|
|
464
|
+
['write', field.groups.write],
|
|
465
|
+
]) {
|
|
466
|
+
for (const code of codes) {
|
|
467
|
+
if (!securityGroups.has(code))
|
|
468
|
+
throw new InvalidModuleError(`${where} restricts ${kind} to the group '${code}', which no module declares.`, 'Declare it with defineGroup() in a module the field can see, or fix the code.');
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
if (field.sequence !== undefined) {
|
|
472
|
+
const definition = sequences.get(field.sequence.code);
|
|
473
|
+
if (definition === undefined)
|
|
474
|
+
throw new UnknownSequenceError(field.sequence.code, where);
|
|
475
|
+
if (field.sequence.gapless !== undefined && field.sequence.gapless !== definition.gapless) {
|
|
476
|
+
throw new InvalidModuleError(`${where} declares the sequence '${definition.code}' as ${field.sequence.gapless ? 'gapless' : 'standard'}, but the definition says ${definition.gapless ? 'gapless' : 'standard'}.`, 'The definition is authoritative: drop gapless from the field, or change the definition.');
|
|
477
|
+
}
|
|
478
|
+
if (field.sequence.dateField !== undefined &&
|
|
479
|
+
model.fields[field.sequence.dateField] === undefined) {
|
|
480
|
+
throw new InvalidModuleError(`${where} names dateField '${field.sequence.dateField}', which is not a field of '${model.name}'.`, 'Point dateField at a date / datetime field of the model.');
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
for (const path of field.depends) {
|
|
484
|
+
let current = registered;
|
|
485
|
+
const segments = path.split('.');
|
|
486
|
+
segments.forEach((segment, i) => {
|
|
487
|
+
const step = current.model.fields[segment];
|
|
488
|
+
if (segment === '' || step === undefined) {
|
|
489
|
+
throw new InvalidDependsPathError(`The depends path '${path}' of ${where} is invalid: '${segment}' is not a field of '${current.model.name}'.`, `Use dotted paths through real fields, e.g. 'lines.subtotal'. Fields of '${current.model.name}': ${Object.keys(current.model.fields).join(', ')}.`);
|
|
490
|
+
}
|
|
491
|
+
if (i < segments.length - 1) {
|
|
492
|
+
const next = targetOf(step);
|
|
493
|
+
if (next === undefined) {
|
|
494
|
+
throw new InvalidDependsPathError(`The depends path '${path}' of ${where} is invalid: '${segment}' is a ${step.kind} field and cannot be traversed.`, 'Only many2one, one2many and many2many fields can be followed by another segment.');
|
|
495
|
+
}
|
|
496
|
+
current = resolve(fromModule, next, `the depends path '${path}' of ${where}`);
|
|
497
|
+
}
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
const enforce = options.security?.enforce ?? true;
|
|
503
|
+
const mode = enforce === 'warn' ? 'warn' : enforce ? 'enforce' : 'off';
|
|
504
|
+
if (mode === 'warn' && process.env['NODE_ENV'] === 'production') {
|
|
505
|
+
throw new SecurityDefinitionError("security: { enforce: 'warn' } is refused when NODE_ENV=production.", "Declare the missing access grants (the warnings name them) and remove enforce: 'warn'.");
|
|
506
|
+
}
|
|
507
|
+
const reported = new Set();
|
|
508
|
+
const onDenied = options.security?.onDenied ??
|
|
509
|
+
((message) => {
|
|
510
|
+
process.emitWarning(message, { code: 'SHUTRO_ACCESS_WOULD_DENY' });
|
|
511
|
+
});
|
|
512
|
+
// Related fields mirror a field of the same kind at the end of their path (many2one steps only).
|
|
513
|
+
for (const { model } of models.values()) {
|
|
514
|
+
for (const [key, field] of Object.entries(model.fields)) {
|
|
515
|
+
const path = relatedPath(field.compute);
|
|
516
|
+
if (path === undefined)
|
|
517
|
+
continue;
|
|
518
|
+
const where = `Related field '${key}' of ${model.name} ('${path}')`;
|
|
519
|
+
let current = model;
|
|
520
|
+
const steps = path.split('.');
|
|
521
|
+
for (const [i, step] of steps.entries()) {
|
|
522
|
+
const f = current.fields[step];
|
|
523
|
+
if (f === undefined)
|
|
524
|
+
throw new InvalidRelationError(`${where}: '${step}' is not a field of ${current.name}.`, 'Fix the path.');
|
|
525
|
+
if (i === steps.length - 1) {
|
|
526
|
+
const sameTarget = f.kind !== 'many2one' || targetOf(f) === targetOf(field);
|
|
527
|
+
if (f.kind !== field.kind || !sameTarget)
|
|
528
|
+
throw new InvalidRelationError(`${where} is a ${field.kind}${field.kind === 'many2one' ? ` of ${targetOf(field)}` : ''}, but the path ends at a ${f.kind}${f.kind === 'many2one' ? ` of ${targetOf(f)}` : ''}.`, 'Declare the related field with the same kind (and target) as the field it mirrors.');
|
|
529
|
+
break;
|
|
530
|
+
}
|
|
531
|
+
if (f.kind !== 'many2one')
|
|
532
|
+
throw new InvalidRelationError(`${where}: '${step}' is a ${f.kind}; related paths go through many2one fields.`, 'Use a compute for x2many paths.');
|
|
533
|
+
const next = models.get(targetOf(f) ?? '');
|
|
534
|
+
if (next === undefined)
|
|
535
|
+
break; // the relation check reports unknown targets
|
|
536
|
+
current = next.model;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
const externalIds = validateData(modules, models);
|
|
541
|
+
const registry = {
|
|
542
|
+
modules: Object.freeze(modules),
|
|
543
|
+
compute: buildComputeGraph(models),
|
|
544
|
+
sequences,
|
|
545
|
+
externalIds,
|
|
546
|
+
security: {
|
|
547
|
+
groups: securityGroups,
|
|
548
|
+
closure: (codes) => groupClosure(securityGroups, codes),
|
|
549
|
+
isAdministrator: (groups) => [...administrators].some((code) => groups.has(code)),
|
|
550
|
+
permissions,
|
|
551
|
+
enforce: mode !== 'off',
|
|
552
|
+
mode,
|
|
553
|
+
denied(message) {
|
|
554
|
+
if (reported.has(message))
|
|
555
|
+
return;
|
|
556
|
+
reported.add(message);
|
|
557
|
+
onDenied(message);
|
|
558
|
+
},
|
|
559
|
+
},
|
|
560
|
+
loadOrder: Object.freeze(modules.map((m) => m.name)),
|
|
561
|
+
models,
|
|
562
|
+
has: (name) => models.has(name),
|
|
563
|
+
get(name) {
|
|
564
|
+
const found = models.get(name);
|
|
565
|
+
if (found === undefined)
|
|
566
|
+
throw new UnknownModelError(name, undefined);
|
|
567
|
+
return found;
|
|
568
|
+
},
|
|
569
|
+
describe(name) {
|
|
570
|
+
const registered = registry.get(name);
|
|
571
|
+
const base = registered.model.describe();
|
|
572
|
+
return {
|
|
573
|
+
...base,
|
|
574
|
+
origin: { module: registered.module },
|
|
575
|
+
extensions: registered.extensions,
|
|
576
|
+
fields: Object.fromEntries(Object.entries(base.fields).map(([key, field]) => [
|
|
577
|
+
key,
|
|
578
|
+
{ ...field, origin: { module: registered.fieldOrigins[key] ?? registered.module } },
|
|
579
|
+
])),
|
|
580
|
+
methodLayers: registered.methodLayers,
|
|
581
|
+
};
|
|
582
|
+
},
|
|
583
|
+
explain(model, method) {
|
|
584
|
+
const layers = registry.get(model).methodLayers[method];
|
|
585
|
+
if (layers === undefined)
|
|
586
|
+
throw new UnknownModelError(`${model}.${method}`, 'explain()');
|
|
587
|
+
return layers;
|
|
588
|
+
},
|
|
589
|
+
};
|
|
590
|
+
return Object.freeze(registry);
|
|
591
|
+
}
|