shutro 0.0.0-stage → 0.1.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 +89 -2
- package/dist/audit/index.d.ts +57 -0
- package/dist/audit/index.js +94 -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 +149 -0
- package/dist/cli/config.d.ts +18 -0
- package/dist/cli/config.js +47 -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 +82 -0
- package/dist/cli/generate/render.d.ts +23 -0
- package/dist/cli/generate/render.js +200 -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/core/compute/graph.d.ts +52 -0
- package/dist/core/compute/graph.js +162 -0
- package/dist/core/env/env.d.ts +295 -0
- package/dist/core/env/env.js +631 -0
- package/dist/core/env/identity.d.ts +33 -0
- package/dist/core/env/identity.js +49 -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 +242 -0
- package/dist/core/errors.js +339 -0
- package/dist/core/index.d.ts +43 -0
- package/dist/core/index.js +34 -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 +446 -0
- package/dist/core/model/field.js +398 -0
- package/dist/core/model/generated.d.ts +75 -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 +347 -0
- package/dist/core/model/model.js +538 -0
- package/dist/core/model/partition.d.ts +31 -0
- package/dist/core/model/partition.js +71 -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 +60 -0
- package/dist/core/money/fx.js +109 -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/audit.d.ts +25 -0
- package/dist/core/recordset/audit.js +205 -0
- package/dist/core/recordset/compute.d.ts +34 -0
- package/dist/core/recordset/compute.js +405 -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 +27 -0
- package/dist/core/recordset/domain.js +228 -0
- package/dist/core/recordset/onchange.d.ts +43 -0
- package/dist/core/recordset/onchange.js +207 -0
- package/dist/core/recordset/recordset.d.ts +101 -0
- package/dist/core/recordset/recordset.js +723 -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 +42 -0
- package/dist/core/recordset/security.js +184 -0
- package/dist/core/recordset/sequences.d.ts +31 -0
- package/dist/core/recordset/sequences.js +154 -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 +77 -0
- package/dist/core/recordset/types.d.ts +296 -0
- package/dist/core/recordset/types.js +8 -0
- package/dist/core/recordset/values.d.ts +27 -0
- package/dist/core/recordset/values.js +147 -0
- package/dist/core/recordset/writes.d.ts +37 -0
- package/dist/core/recordset/writes.js +581 -0
- package/dist/core/registry/ddl.d.ts +22 -0
- package/dist/core/registry/ddl.js +127 -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 +80 -0
- package/dist/core/registry/module.js +96 -0
- package/dist/core/registry/registry.d.ts +105 -0
- package/dist/core/registry/registry.js +496 -0
- package/dist/driver-pg/driver.d.ts +86 -0
- package/dist/driver-pg/driver.js +176 -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 +195 -0
- package/dist/security/index.d.ts +123 -0
- package/dist/security/index.js +262 -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 +42 -0
- package/dist/sql/tag.js +95 -0
- package/package.json +82 -4
|
@@ -0,0 +1,496 @@
|
|
|
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, transitionOf, } from '../model/model.js';
|
|
9
|
+
import { isModule } from './module.js';
|
|
10
|
+
// ------------------------------------------------------------------------------------------------- schema types
|
|
11
|
+
import { groupClosure, mergeAccess, normalizeFieldGroups, } from '../../security/index.js';
|
|
12
|
+
import { buildComputeGraph } from '../compute/graph.js';
|
|
13
|
+
const RELATION_KINDS = new Set(['many2one', 'one2many', 'many2many']);
|
|
14
|
+
/** The target model of a relation field, else `undefined`. */
|
|
15
|
+
export function targetOf(field) {
|
|
16
|
+
return RELATION_KINDS.has(field.kind)
|
|
17
|
+
? field.target
|
|
18
|
+
: undefined;
|
|
19
|
+
}
|
|
20
|
+
// ----------------------------------------------------------------------------------------------------- loading
|
|
21
|
+
/** Collects every module reachable from the roots and checks that names are unique. */
|
|
22
|
+
function collect(roots) {
|
|
23
|
+
const byName = new Map();
|
|
24
|
+
const visit = (module) => {
|
|
25
|
+
if (!isModule(module))
|
|
26
|
+
throw new DuplicateModuleError(String(module.name ?? '?'));
|
|
27
|
+
const known = byName.get(module.name);
|
|
28
|
+
if (known === module)
|
|
29
|
+
return;
|
|
30
|
+
if (known !== undefined)
|
|
31
|
+
throw new DuplicateModuleError(module.name);
|
|
32
|
+
byName.set(module.name, module);
|
|
33
|
+
for (const dep of module.depends)
|
|
34
|
+
visit(dep);
|
|
35
|
+
};
|
|
36
|
+
for (const root of roots)
|
|
37
|
+
visit(root);
|
|
38
|
+
return byName;
|
|
39
|
+
}
|
|
40
|
+
/** Kahn's algorithm with the smallest name first: the order is a pure function of the module set (RFC 0002 R5). */
|
|
41
|
+
function order(byName) {
|
|
42
|
+
const remaining = new Map();
|
|
43
|
+
for (const [name, module] of byName)
|
|
44
|
+
remaining.set(name, new Set(module.depends.map((d) => d.name)));
|
|
45
|
+
const result = [];
|
|
46
|
+
while (remaining.size > 0) {
|
|
47
|
+
const ready = [...remaining.entries()]
|
|
48
|
+
.filter(([, deps]) => deps.size === 0)
|
|
49
|
+
.map(([name]) => name)
|
|
50
|
+
.sort();
|
|
51
|
+
const next = ready[0];
|
|
52
|
+
if (next === undefined) {
|
|
53
|
+
// Unreachable with module objects (a module can't depend on one defined after it), kept as a guard.
|
|
54
|
+
throw new DuplicateModuleError([...remaining.keys()].join(' → '));
|
|
55
|
+
}
|
|
56
|
+
const module = byName.get(next);
|
|
57
|
+
if (module !== undefined)
|
|
58
|
+
result.push(module);
|
|
59
|
+
remaining.delete(next);
|
|
60
|
+
for (const deps of remaining.values())
|
|
61
|
+
deps.delete(next);
|
|
62
|
+
}
|
|
63
|
+
return result;
|
|
64
|
+
}
|
|
65
|
+
/** Transitive dependency names of a module, including itself. */
|
|
66
|
+
function closure(module) {
|
|
67
|
+
const names = new Set();
|
|
68
|
+
const walk = (m) => {
|
|
69
|
+
if (names.has(m.name))
|
|
70
|
+
return;
|
|
71
|
+
names.add(m.name);
|
|
72
|
+
for (const dep of m.depends)
|
|
73
|
+
walk(dep);
|
|
74
|
+
};
|
|
75
|
+
walk(module);
|
|
76
|
+
return names;
|
|
77
|
+
}
|
|
78
|
+
function draftOf(model, module) {
|
|
79
|
+
const fieldOrigins = {};
|
|
80
|
+
for (const key of Object.keys(model.fields))
|
|
81
|
+
fieldOrigins[key] = module;
|
|
82
|
+
const methodLayers = {};
|
|
83
|
+
for (const key of Object.keys(model.methods))
|
|
84
|
+
methodLayers[key] = [{ module, kind: 'definition' }];
|
|
85
|
+
const def = model.definition;
|
|
86
|
+
return {
|
|
87
|
+
base: model,
|
|
88
|
+
module,
|
|
89
|
+
extensions: [],
|
|
90
|
+
fields: { ...def.fields },
|
|
91
|
+
fieldOrigins,
|
|
92
|
+
methods: { ...model.methods },
|
|
93
|
+
methodLayers,
|
|
94
|
+
constraints: { ...(def.constraints ?? {}) },
|
|
95
|
+
onchange: { ...(def.onchange ?? {}) },
|
|
96
|
+
access: { ...(def.access ?? {}) },
|
|
97
|
+
rules: { ...(def.rules ?? {}) },
|
|
98
|
+
sqlConstraints: { ...(def.sqlConstraints ?? {}) },
|
|
99
|
+
indexes: [...(def.indexes ?? [])],
|
|
100
|
+
tracking: [...(def.tracking ?? [])],
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
/** Wraps `prev` with `layer`: `layer.call(this, next, ...args)` where `next` is `prev` bound to `this`. */
|
|
104
|
+
function compose(prev, layer) {
|
|
105
|
+
const composed = function composed(...args) {
|
|
106
|
+
const next = (...nextArgs) => prev.apply(this, nextArgs);
|
|
107
|
+
return layer.call(this, next, ...args);
|
|
108
|
+
};
|
|
109
|
+
// A wrapped transition is still the transition (the rebuilt model must not regenerate it, RFC 0010 §7.1).
|
|
110
|
+
const transition = transitionOf(prev);
|
|
111
|
+
return transition === undefined
|
|
112
|
+
? composed
|
|
113
|
+
: markTransition(composed, transition.field, transition.name);
|
|
114
|
+
}
|
|
115
|
+
function applyExtension(draft, ext, module, reachable) {
|
|
116
|
+
const where = `Module '${module}' extending '${ext.name}'`;
|
|
117
|
+
const conflict = (what, key, origin, fix) => {
|
|
118
|
+
const problem = reachable.has(origin)
|
|
119
|
+
? `${where}: ${what} '${key}' already exists (from '${origin}').`
|
|
120
|
+
: `${what} '${key}' of '${ext.name}' is added by both '${origin}' and '${module}', which do not depend on each other.`;
|
|
121
|
+
throw new ExtensionConflictError(problem, fix);
|
|
122
|
+
};
|
|
123
|
+
for (const [key, field] of Object.entries(ext.fields)) {
|
|
124
|
+
const origin = draft.fieldOrigins[key];
|
|
125
|
+
if (origin !== undefined) {
|
|
126
|
+
conflict('field', key, origin, reachable.has(origin)
|
|
127
|
+
? 'Use fieldOverrides to change an existing field.'
|
|
128
|
+
: 'Rename one field, or make one module depend on the other and use fieldOverrides.');
|
|
129
|
+
}
|
|
130
|
+
if (field.required &&
|
|
131
|
+
field.default === undefined &&
|
|
132
|
+
!field.computed &&
|
|
133
|
+
field.kind !== 'boolean' &&
|
|
134
|
+
// x2many relations are "required" only in the sense that they always hold a (possibly empty) list.
|
|
135
|
+
field.kind !== 'one2many' &&
|
|
136
|
+
field.kind !== 'many2many') {
|
|
137
|
+
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.');
|
|
138
|
+
}
|
|
139
|
+
draft.fields[key] = field;
|
|
140
|
+
draft.fieldOrigins[key] = module;
|
|
141
|
+
}
|
|
142
|
+
for (const [key, override] of Object.entries(ext.fieldOverrides)) {
|
|
143
|
+
const field = draft.fields[key];
|
|
144
|
+
if (field === undefined) {
|
|
145
|
+
const implicit = draft.base.fields[key] !== undefined;
|
|
146
|
+
throw new InvalidExtensionError(`${where}: fieldOverrides names '${key}', which is ${implicit ? 'an implicit field' : 'not a field'} of '${ext.name}'.`, implicit
|
|
147
|
+
? 'Implicit fields (id, createdAt, company, ...) cannot be overridden.'
|
|
148
|
+
: `Fields: ${Object.keys(draft.fields).join(', ')}.`);
|
|
149
|
+
}
|
|
150
|
+
const changes = {};
|
|
151
|
+
for (const [attr, value] of Object.entries(override)) {
|
|
152
|
+
if (value === undefined)
|
|
153
|
+
continue;
|
|
154
|
+
switch (attr) {
|
|
155
|
+
case 'label':
|
|
156
|
+
case 'help':
|
|
157
|
+
case 'default':
|
|
158
|
+
case 'index':
|
|
159
|
+
case 'tracking':
|
|
160
|
+
case 'copy':
|
|
161
|
+
Object.assign(changes, { [attr]: value });
|
|
162
|
+
break;
|
|
163
|
+
case 'groups':
|
|
164
|
+
Object.assign(changes, { groups: normalizeFieldGroups(value) });
|
|
165
|
+
break;
|
|
166
|
+
case 'required': {
|
|
167
|
+
if (value === false && field.required) {
|
|
168
|
+
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.');
|
|
169
|
+
}
|
|
170
|
+
if (value === true &&
|
|
171
|
+
!field.required &&
|
|
172
|
+
override.default === undefined &&
|
|
173
|
+
field.default === undefined) {
|
|
174
|
+
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.');
|
|
175
|
+
}
|
|
176
|
+
Object.assign(changes, { required: value });
|
|
177
|
+
break;
|
|
178
|
+
}
|
|
179
|
+
case 'selectionAdd': {
|
|
180
|
+
const selectable = field;
|
|
181
|
+
if ((field.kind !== 'selection' && field.kind !== 'state') ||
|
|
182
|
+
typeof selectable.selection === 'function') {
|
|
183
|
+
throw new InvalidExtensionError(`${where}: fieldOverrides.${key}.selectionAdd on a ${field.kind} field.`, 'selectionAdd applies to selection and state fields with a static map.');
|
|
184
|
+
}
|
|
185
|
+
if (selectable.extensible !== true) {
|
|
186
|
+
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.');
|
|
187
|
+
}
|
|
188
|
+
const existing = selectable.selection ?? [];
|
|
189
|
+
const added = Object.entries(value).filter(([k]) => !existing.some(([e]) => e === k));
|
|
190
|
+
changes.selection = [...existing, ...added.map(([k, v]) => [k, v])];
|
|
191
|
+
break;
|
|
192
|
+
}
|
|
193
|
+
case 'statesAdd':
|
|
194
|
+
case 'transitionsAdd': {
|
|
195
|
+
const stateField = field;
|
|
196
|
+
if (field.kind !== 'state') {
|
|
197
|
+
throw new InvalidExtensionError(`${where}: fieldOverrides.${key}.${attr} on a ${field.kind} field.`, 'statesAdd / transitionsAdd apply to state fields.');
|
|
198
|
+
}
|
|
199
|
+
if (stateField.extensible !== true) {
|
|
200
|
+
throw new InvalidExtensionError(`${where}: '${key}' is not an extensible state field.`, 'The owner must declare the field with extensible: true (RFC 0002 S6).');
|
|
201
|
+
}
|
|
202
|
+
const selection = [...(changes.selection ?? stateField.selection ?? [])];
|
|
203
|
+
const hooks = {
|
|
204
|
+
...(changes.stateHooks ?? stateField.stateHooks ?? {}),
|
|
205
|
+
};
|
|
206
|
+
const transitions = {
|
|
207
|
+
...(changes.transitions ?? stateField.transitions ?? {}),
|
|
208
|
+
};
|
|
209
|
+
if (attr === 'statesAdd') {
|
|
210
|
+
for (const [s, spec] of Object.entries(value)) {
|
|
211
|
+
if (selection.some(([e]) => e === s))
|
|
212
|
+
throw new InvalidExtensionError(`${where}: state '${s}' already exists on '${key}'.`, 'Add new states only (RFC 0002 S6).');
|
|
213
|
+
selection.push([s, typeof spec === 'string' ? spec : spec.label]);
|
|
214
|
+
if (typeof spec !== 'string' &&
|
|
215
|
+
(spec.onEnter !== undefined || spec.onExit !== undefined))
|
|
216
|
+
hooks[s] = {
|
|
217
|
+
...(spec.onEnter === undefined ? {} : { onEnter: spec.onEnter }),
|
|
218
|
+
...(spec.onExit === undefined ? {} : { onExit: spec.onExit }),
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
Object.assign(changes, { selection, stateHooks: hooks });
|
|
222
|
+
}
|
|
223
|
+
else {
|
|
224
|
+
const states = new Set(selection.map(([s]) => s));
|
|
225
|
+
for (const [tname, t] of Object.entries(value)) {
|
|
226
|
+
if (transitions[tname] !== undefined)
|
|
227
|
+
throw new InvalidExtensionError(`${where}: transition '${tname}' already exists on '${key}'.`, 'Add new transitions only; wrap existing ones with overrides (RFC 0002 S6).');
|
|
228
|
+
for (const s of [...t.from, t.to]) {
|
|
229
|
+
if (!states.has(s))
|
|
230
|
+
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).`);
|
|
231
|
+
}
|
|
232
|
+
transitions[tname] = t;
|
|
233
|
+
draft.methodLayers[tname] = [{ module, kind: 'definition' }];
|
|
234
|
+
}
|
|
235
|
+
Object.assign(changes, { transitions });
|
|
236
|
+
}
|
|
237
|
+
break;
|
|
238
|
+
}
|
|
239
|
+
default:
|
|
240
|
+
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).');
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
draft.fields[key] = overrideField(field, changes);
|
|
244
|
+
}
|
|
245
|
+
for (const [key, fn] of Object.entries(ext.methods)) {
|
|
246
|
+
const layers = draft.methodLayers[key];
|
|
247
|
+
if (layers !== undefined) {
|
|
248
|
+
const origin = layers[0]?.module ?? draft.module;
|
|
249
|
+
conflict('method', key, origin, reachable.has(origin)
|
|
250
|
+
? 'Use overrides to wrap an existing method.'
|
|
251
|
+
: 'Rename one method, or make one module depend on the other and use overrides.');
|
|
252
|
+
}
|
|
253
|
+
draft.methods[key] = fn;
|
|
254
|
+
draft.methodLayers[key] = [{ module, kind: 'definition' }];
|
|
255
|
+
}
|
|
256
|
+
for (const [key, { kind, fn }] of Object.entries(ext.overrides)) {
|
|
257
|
+
const prev = draft.methods[key];
|
|
258
|
+
if (prev === undefined) {
|
|
259
|
+
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\`.`);
|
|
260
|
+
}
|
|
261
|
+
draft.methods[key] = kind === 'replace' ? fn : compose(prev, fn);
|
|
262
|
+
draft.methodLayers[key] = [...(draft.methodLayers[key] ?? []), { module, kind }];
|
|
263
|
+
}
|
|
264
|
+
for (const [key, spec] of Object.entries(ext.constraints)) {
|
|
265
|
+
if (draft.constraints[key] !== undefined)
|
|
266
|
+
conflict('constraint', key, draft.module, 'Use a different constraint key.');
|
|
267
|
+
draft.constraints[key] = spec;
|
|
268
|
+
}
|
|
269
|
+
draft.access = mergeAccess(draft.access, ext.access);
|
|
270
|
+
for (const [key, rule] of Object.entries(ext.rules)) {
|
|
271
|
+
if (draft.rules[key] !== undefined)
|
|
272
|
+
conflict('rule', key, draft.module, 'Use a different rule key.');
|
|
273
|
+
draft.rules[key] = rule;
|
|
274
|
+
}
|
|
275
|
+
for (const [key, fn] of Object.entries(ext.onchange)) {
|
|
276
|
+
if (draft.onchange[key] !== undefined)
|
|
277
|
+
conflict('onchange', key, draft.module, 'Call a shared method from the existing handler instead.');
|
|
278
|
+
draft.onchange[key] = fn;
|
|
279
|
+
}
|
|
280
|
+
for (const [key, spec] of Object.entries(ext.sqlConstraints)) {
|
|
281
|
+
if (draft.sqlConstraints[key] !== undefined)
|
|
282
|
+
conflict('sqlConstraints', key, draft.module, 'Use a different key (prefix it with the module name).');
|
|
283
|
+
draft.sqlConstraints[key] = spec;
|
|
284
|
+
}
|
|
285
|
+
draft.indexes.push(...ext.indexes);
|
|
286
|
+
for (const key of ext.tracking)
|
|
287
|
+
if (!draft.tracking.includes(key))
|
|
288
|
+
draft.tracking.push(key);
|
|
289
|
+
draft.extensions.push(module);
|
|
290
|
+
}
|
|
291
|
+
/** Rebuilds the final model from the draft through `defineModel`, so every model-level check applies to it. */
|
|
292
|
+
function finalize(draft) {
|
|
293
|
+
const def = draft.base.definition;
|
|
294
|
+
const model = defineModel(draft.base.name, {
|
|
295
|
+
...def,
|
|
296
|
+
fields: draft.fields,
|
|
297
|
+
methods: draft.methods,
|
|
298
|
+
constraints: draft.constraints,
|
|
299
|
+
onchange: draft.onchange,
|
|
300
|
+
access: draft.access,
|
|
301
|
+
rules: draft.rules,
|
|
302
|
+
sqlConstraints: draft.sqlConstraints,
|
|
303
|
+
indexes: draft.indexes,
|
|
304
|
+
tracking: draft.tracking,
|
|
305
|
+
});
|
|
306
|
+
const fieldOrigins = {};
|
|
307
|
+
for (const key of Object.keys(model.fields))
|
|
308
|
+
fieldOrigins[key] = draft.fieldOrigins[key] ?? draft.module;
|
|
309
|
+
return {
|
|
310
|
+
model,
|
|
311
|
+
module: draft.module,
|
|
312
|
+
extensions: Object.freeze([...draft.extensions]),
|
|
313
|
+
fieldOrigins: Object.freeze(fieldOrigins),
|
|
314
|
+
methodLayers: Object.freeze(Object.fromEntries(Object.entries(draft.methodLayers).map(([k, v]) => [k, Object.freeze([...v])]))),
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
// -------------------------------------------------------------------------------------------------- building
|
|
318
|
+
/**
|
|
319
|
+
* Builds the registry: collects and orders modules, registers models, applies extensions in load order under the
|
|
320
|
+
* view-safety rules, and runs the checks that need every model: relation targets exist and belong to a declared
|
|
321
|
+
* dependency, one2many inverses point back, `depends` paths resolve.
|
|
322
|
+
*
|
|
323
|
+
* @throws {DuplicateModuleError} {DuplicateModelError} {UnknownModelError} {UndeclaredDependencyError}
|
|
324
|
+
* {InvalidRelationError} {InvalidDependsPathError} {InvalidExtensionError} {ExtensionConflictError}
|
|
325
|
+
*/
|
|
326
|
+
export function buildRegistry(options) {
|
|
327
|
+
const modules = order(collect(options.modules));
|
|
328
|
+
const closures = new Map(modules.map((m) => [m.name, closure(m)]));
|
|
329
|
+
const drafts = new Map();
|
|
330
|
+
for (const module of modules) {
|
|
331
|
+
for (const model of module.models) {
|
|
332
|
+
const existing = drafts.get(model.name);
|
|
333
|
+
if (existing !== undefined)
|
|
334
|
+
throw new DuplicateModelError(model.name, [existing.module, module.name]);
|
|
335
|
+
drafts.set(model.name, draftOf(model, module.name));
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
for (const module of modules) {
|
|
339
|
+
const reachable = closures.get(module.name) ?? new Set();
|
|
340
|
+
for (const ext of module.extensions) {
|
|
341
|
+
const draft = drafts.get(ext.name);
|
|
342
|
+
if (draft === undefined)
|
|
343
|
+
throw new UnknownModelError(ext.name, `the extension in module '${module.name}'`);
|
|
344
|
+
if (!reachable.has(draft.module))
|
|
345
|
+
throw new UndeclaredDependencyError(module.name, ext.name, draft.module, 'an extension');
|
|
346
|
+
applyExtension(draft, ext, module.name, reachable);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const models = new Map();
|
|
350
|
+
for (const [name, draft] of drafts)
|
|
351
|
+
models.set(name, finalize(draft));
|
|
352
|
+
const resolve = (fromModule, target, via) => {
|
|
353
|
+
const found = models.get(target);
|
|
354
|
+
if (found === undefined)
|
|
355
|
+
throw new UnknownModelError(target, via);
|
|
356
|
+
if (!closures.get(fromModule)?.has(found.module))
|
|
357
|
+
throw new UndeclaredDependencyError(fromModule, target, found.module, via);
|
|
358
|
+
return found;
|
|
359
|
+
};
|
|
360
|
+
const securityGroups = new Map();
|
|
361
|
+
for (const module of modules) {
|
|
362
|
+
for (const group of module.groups) {
|
|
363
|
+
if (securityGroups.has(group.code)) {
|
|
364
|
+
throw new InvalidModuleError(`Module '${module.name}' declares the group '${group.code}', which another module already declares.`, 'Group codes are global: declare each group once.');
|
|
365
|
+
}
|
|
366
|
+
securityGroups.set(group.code, group);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
for (const { model } of models.values()) {
|
|
370
|
+
for (const code of [
|
|
371
|
+
...Object.keys(model.access),
|
|
372
|
+
...Object.values(model.rules).flatMap((r) => (r.groups === 'global' ? [] : [...r.groups])),
|
|
373
|
+
]) {
|
|
374
|
+
if (!securityGroups.has(code))
|
|
375
|
+
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.');
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
const sequences = new Map();
|
|
379
|
+
for (const module of modules) {
|
|
380
|
+
for (const definition of module.sequences) {
|
|
381
|
+
if (sequences.has(definition.code)) {
|
|
382
|
+
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.');
|
|
383
|
+
}
|
|
384
|
+
sequences.set(definition.code, definition);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
for (const registered of models.values()) {
|
|
388
|
+
const { model } = registered;
|
|
389
|
+
for (const [key, field] of Object.entries(model.fields)) {
|
|
390
|
+
const where = `field '${key}' of model '${model.name}'`;
|
|
391
|
+
const fromModule = registered.fieldOrigins[key] ?? registered.module;
|
|
392
|
+
const target = targetOf(field);
|
|
393
|
+
if (target !== undefined) {
|
|
394
|
+
const other = resolve(fromModule, target, where);
|
|
395
|
+
if (field.kind !== 'one2many' && other.model.partition !== undefined) {
|
|
396
|
+
throw new InvalidRelationError(`${where} points at '${target}', which is partitioned.`, 'A foreign key cannot reference a partitioned table without its partition key: reference a non-partitioned model, or store the id in a plain integer field.');
|
|
397
|
+
}
|
|
398
|
+
if (field.kind === 'one2many') {
|
|
399
|
+
const inverseKey = field.inverseField;
|
|
400
|
+
const inverse = other.model.fields[inverseKey];
|
|
401
|
+
if (inverse === undefined ||
|
|
402
|
+
inverse.kind !== 'many2one' ||
|
|
403
|
+
targetOf(inverse) !== model.name) {
|
|
404
|
+
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.`);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
if (field.kind === 'many2one' &&
|
|
409
|
+
field.checkCompany === true) {
|
|
410
|
+
const targetName = targetOf(field) ?? '';
|
|
411
|
+
const targetModel = resolve(fromModule, targetName, where).model;
|
|
412
|
+
if (targetModel.companyScoped === undefined) {
|
|
413
|
+
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.');
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
for (const [kind, codes] of [
|
|
417
|
+
['read', field.groups.read],
|
|
418
|
+
['write', field.groups.write],
|
|
419
|
+
]) {
|
|
420
|
+
for (const code of codes) {
|
|
421
|
+
if (!securityGroups.has(code))
|
|
422
|
+
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.');
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
if (field.sequence !== undefined) {
|
|
426
|
+
const definition = sequences.get(field.sequence.code);
|
|
427
|
+
if (definition === undefined)
|
|
428
|
+
throw new UnknownSequenceError(field.sequence.code, where);
|
|
429
|
+
if (field.sequence.gapless !== undefined && field.sequence.gapless !== definition.gapless) {
|
|
430
|
+
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.');
|
|
431
|
+
}
|
|
432
|
+
if (field.sequence.dateField !== undefined &&
|
|
433
|
+
model.fields[field.sequence.dateField] === undefined) {
|
|
434
|
+
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.');
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
for (const path of field.depends) {
|
|
438
|
+
let current = registered;
|
|
439
|
+
const segments = path.split('.');
|
|
440
|
+
segments.forEach((segment, i) => {
|
|
441
|
+
const step = current.model.fields[segment];
|
|
442
|
+
if (segment === '' || step === undefined) {
|
|
443
|
+
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(', ')}.`);
|
|
444
|
+
}
|
|
445
|
+
if (i < segments.length - 1) {
|
|
446
|
+
const next = targetOf(step);
|
|
447
|
+
if (next === undefined) {
|
|
448
|
+
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.');
|
|
449
|
+
}
|
|
450
|
+
current = resolve(fromModule, next, `the depends path '${path}' of ${where}`);
|
|
451
|
+
}
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
const registry = {
|
|
457
|
+
modules: Object.freeze(modules),
|
|
458
|
+
compute: buildComputeGraph(models),
|
|
459
|
+
sequences,
|
|
460
|
+
security: {
|
|
461
|
+
groups: securityGroups,
|
|
462
|
+
closure: (codes) => groupClosure(securityGroups, codes),
|
|
463
|
+
enforce: options.security?.enforce ?? true,
|
|
464
|
+
},
|
|
465
|
+
loadOrder: Object.freeze(modules.map((m) => m.name)),
|
|
466
|
+
models,
|
|
467
|
+
has: (name) => models.has(name),
|
|
468
|
+
get(name) {
|
|
469
|
+
const found = models.get(name);
|
|
470
|
+
if (found === undefined)
|
|
471
|
+
throw new UnknownModelError(name, undefined);
|
|
472
|
+
return found;
|
|
473
|
+
},
|
|
474
|
+
describe(name) {
|
|
475
|
+
const registered = registry.get(name);
|
|
476
|
+
const base = registered.model.describe();
|
|
477
|
+
return {
|
|
478
|
+
...base,
|
|
479
|
+
origin: { module: registered.module },
|
|
480
|
+
extensions: registered.extensions,
|
|
481
|
+
fields: Object.fromEntries(Object.entries(base.fields).map(([key, field]) => [
|
|
482
|
+
key,
|
|
483
|
+
{ ...field, origin: { module: registered.fieldOrigins[key] ?? registered.module } },
|
|
484
|
+
])),
|
|
485
|
+
methodLayers: registered.methodLayers,
|
|
486
|
+
};
|
|
487
|
+
},
|
|
488
|
+
explain(model, method) {
|
|
489
|
+
const layers = registry.get(model).methodLayers[method];
|
|
490
|
+
if (layers === undefined)
|
|
491
|
+
throw new UnknownModelError(`${model}.${method}`, 'explain()');
|
|
492
|
+
return layers;
|
|
493
|
+
},
|
|
494
|
+
};
|
|
495
|
+
return Object.freeze(registry);
|
|
496
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/** SQL ready to execute. `CompiledSql` from `@shutro/sql` satisfies this structurally. */
|
|
2
|
+
export interface DriverQuery {
|
|
3
|
+
readonly text: string;
|
|
4
|
+
readonly params: readonly unknown[];
|
|
5
|
+
}
|
|
6
|
+
/** A result row. */
|
|
7
|
+
export type Row = Record<string, unknown>;
|
|
8
|
+
/** Transaction isolation level. */
|
|
9
|
+
export type Isolation = 'read committed' | 'repeatable read' | 'serializable';
|
|
10
|
+
/** Options for {@link Driver.transaction}. */
|
|
11
|
+
export interface TxOptions {
|
|
12
|
+
/** Defaults to `repeatable read` (RFC 0003 §7.5). */
|
|
13
|
+
readonly isolation?: Isolation;
|
|
14
|
+
/** `BEGIN … READ ONLY`. Writes fail with `ReadOnlyTransactionError`. */
|
|
15
|
+
readonly readOnly?: boolean;
|
|
16
|
+
/** Session settings for this transaction only (`set_config(name, value, true)`), e.g. `{ 'shutro.user_id': '42' }`. */
|
|
17
|
+
readonly settings?: Readonly<Record<string, string>>;
|
|
18
|
+
/** `statement_timeout` for this transaction. */
|
|
19
|
+
readonly statementTimeoutMs?: number;
|
|
20
|
+
/** `lock_timeout` for this transaction. */
|
|
21
|
+
readonly lockTimeoutMs?: number;
|
|
22
|
+
}
|
|
23
|
+
/** A connection inside a transaction (or savepoint). */
|
|
24
|
+
export interface DriverConnection {
|
|
25
|
+
/** Runs one statement. */
|
|
26
|
+
query<R extends Row = Row>(query: DriverQuery): Promise<readonly R[]>;
|
|
27
|
+
/** Runs a query through a server-side cursor, yielding batches of at most `batchSize` rows (RFC 0004 §7.7). */
|
|
28
|
+
stream<R extends Row = Row>(query: DriverQuery, batchSize: number): AsyncIterable<readonly R[]>;
|
|
29
|
+
/** Runs `fn` in a savepoint: rolled back if `fn` throws (and the error rethrown), released otherwise. */
|
|
30
|
+
savepoint<T>(fn: (conn: DriverConnection) => Promise<T>): Promise<T>;
|
|
31
|
+
/** `COPY … FROM STDIN` with one text-format line per item (tab-separated). Returns the number of lines written. */
|
|
32
|
+
copyIn(query: DriverQuery, lines: Iterable<string> | AsyncIterable<string>): Promise<number>;
|
|
33
|
+
}
|
|
34
|
+
/** The connection pool. */
|
|
35
|
+
export interface Driver {
|
|
36
|
+
/** Runs one statement in its own implicit transaction (DDL, maintenance). Business code uses `transaction()`. */
|
|
37
|
+
query<R extends Row = Row>(query: DriverQuery): Promise<readonly R[]>;
|
|
38
|
+
/**
|
|
39
|
+
* Runs `fn` in a transaction: committed when `fn` resolves, rolled back when it throws. PostgreSQL errors are
|
|
40
|
+
* mapped to typed `DriverError`s. Retrying is the caller's job (`isRetryable()`), because only the caller knows
|
|
41
|
+
* that `fn` is safe to repeat.
|
|
42
|
+
*/
|
|
43
|
+
transaction<T>(options: TxOptions, fn: (conn: DriverConnection) => Promise<T>): Promise<T>;
|
|
44
|
+
/** `LISTEN` on a dedicated connection. Returns a function that stops listening. */
|
|
45
|
+
listen(channel: string, onMessage: (payload: string) => void): Promise<() => Promise<void>>;
|
|
46
|
+
/** Closes all connections, waiting up to `timeoutSeconds` (default 5) for running queries. */
|
|
47
|
+
end(options?: {
|
|
48
|
+
readonly timeoutSeconds?: number;
|
|
49
|
+
}): Promise<void>;
|
|
50
|
+
}
|
|
51
|
+
/** Options for {@link createDriver}. */
|
|
52
|
+
export interface DriverOptions {
|
|
53
|
+
/** `postgres://user:password@host:port/database`. */
|
|
54
|
+
readonly url: string;
|
|
55
|
+
/** Pool size. Defaults to 10. */
|
|
56
|
+
readonly max?: number;
|
|
57
|
+
/**
|
|
58
|
+
* Parses `numeric` values (OID 1700) from their exact text form. `@shutro/core` passes `toDecimal`. Defaults to
|
|
59
|
+
* returning the string unchanged, which is lossless.
|
|
60
|
+
*/
|
|
61
|
+
readonly parseNumeric?: (text: string) => unknown;
|
|
62
|
+
/** Named prepared statements (default `true`). Behind PgBouncer this needs `max_prepared_statements > 0` (≥ 1.21). */
|
|
63
|
+
readonly prepare?: boolean;
|
|
64
|
+
/**
|
|
65
|
+
* Development guard (RFC 0007 §7.3): reject a query when a string parameter (8+ characters) also appears in its text,
|
|
66
|
+
* which means the text was built by concatenation. Defaults to `true` unless `NODE_ENV === 'production'`.
|
|
67
|
+
*/
|
|
68
|
+
readonly checkParamsInText?: boolean;
|
|
69
|
+
/** Receives server NOTICE messages. Defaults to ignoring them (never `console`). */
|
|
70
|
+
readonly onNotice?: (notice: Readonly<Record<string, unknown>>) => void;
|
|
71
|
+
/** `application_name`, visible in `pg_stat_activity`. Defaults to `'shutro'`. */
|
|
72
|
+
readonly applicationName?: string;
|
|
73
|
+
readonly connectTimeoutSeconds?: number;
|
|
74
|
+
readonly idleTimeoutSeconds?: number;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Creates the PostgreSQL connection pool (postgres.js, RFC 0007). All type handling is configured on this instance;
|
|
78
|
+
* no global state is touched.
|
|
79
|
+
*
|
|
80
|
+
* @example
|
|
81
|
+
* ```ts
|
|
82
|
+
* const driver = createDriver({ url: process.env.DATABASE_URL, parseNumeric: toDecimal });
|
|
83
|
+
* await driver.transaction({ settings: { 'shutro.user_id': '42' } }, (conn) => conn.query(compile(q)));
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
export declare function createDriver(options: DriverOptions): Driver;
|