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,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal DDL from models: tables, primary keys, NOT NULL, foreign keys, junction tables. A stopgap until
|
|
3
|
+
* `@shutro/migrate` exists (Phase 2); used by tests and examples to create a schema from a registry.
|
|
4
|
+
*
|
|
5
|
+
* DDL can't take bind parameters, so statements are built as text from pieces that are validated individually:
|
|
6
|
+
* identifiers through `sql.id` (quoted), type names through a strict pattern, keywords from a fixed table.
|
|
7
|
+
*/
|
|
8
|
+
import { type CompiledSql } from '../../sql/index.js';
|
|
9
|
+
import type { Field } from '../model/field.js';
|
|
10
|
+
import type { AnyModel } from '../model/model.js';
|
|
11
|
+
import { type Registry } from './registry.js';
|
|
12
|
+
/**
|
|
13
|
+
* The database-level `DEFAULT` of a column (feedback #3), in the form PostgreSQL's catalog shows it once casts are
|
|
14
|
+
* stripped, so the migrator's diff is stable: `true` / `false`, unquoted non-negative numbers, quoted strings,
|
|
15
|
+
* `now()` for the timestamps. `null` when the default is a function, the field is translated, encrypted, numbered,
|
|
16
|
+
* computed, or a relation: those stay in the ORM.
|
|
17
|
+
*/
|
|
18
|
+
export declare function columnDefault(key: string, field: Field): string | null;
|
|
19
|
+
/** The history table of a model with `history: true` (RFC 0018 §7.4). */
|
|
20
|
+
export declare function historyTable(model: AnyModel): string;
|
|
21
|
+
/**
|
|
22
|
+
* The history trigger of a model: archives the row as it was before its first change in each transaction (and before
|
|
23
|
+
* a delete) with its validity range, and keeps `updated_at` at the transaction time on every update, so raw SQL
|
|
24
|
+
* writes are versioned too. Idempotent: run after migrations.
|
|
25
|
+
*/
|
|
26
|
+
export declare function historyStatements(registry: Registry): CompiledSql[];
|
|
27
|
+
/**
|
|
28
|
+
* `CREATE TABLE` statements for every model in the registry, then `ALTER TABLE … ADD FOREIGN KEY` for every
|
|
29
|
+
* many2one, then junction tables for many2many fields. Execute them in order.
|
|
30
|
+
*/
|
|
31
|
+
export declare function createTableStatements(registry: Registry): readonly CompiledSql[];
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal DDL from models: tables, primary keys, NOT NULL, foreign keys, junction tables. A stopgap until
|
|
3
|
+
* `@shutro/migrate` exists (Phase 2); used by tests and examples to create a schema from a registry.
|
|
4
|
+
*
|
|
5
|
+
* DDL can't take bind parameters, so statements are built as text from pieces that are validated individually:
|
|
6
|
+
* identifiers through `sql.id` (quoted), type names through a strict pattern, keywords from a fixed table.
|
|
7
|
+
*/
|
|
8
|
+
import { compile, sql } from '../../sql/index.js';
|
|
9
|
+
import { InvalidModelError } from '../errors.js';
|
|
10
|
+
import { junctionTable } from '../recordset/relations.js';
|
|
11
|
+
import { targetOf } from './registry.js';
|
|
12
|
+
const TYPE_NAME = /^[a-z]+( [a-z]+)*(\(\d+(, ?\d+)?\))?$/;
|
|
13
|
+
function ident(...parts) {
|
|
14
|
+
return compile(sql.id(...parts)).text;
|
|
15
|
+
}
|
|
16
|
+
function typeName(field, model, key) {
|
|
17
|
+
if (!TYPE_NAME.test(field.pgType)) {
|
|
18
|
+
throw new InvalidModelError(model, `field '${key}' has an unexpected column type ${JSON.stringify(field.pgType)}.`, 'Column types come from the field builders; this should not happen.');
|
|
19
|
+
}
|
|
20
|
+
return field.pgType;
|
|
21
|
+
}
|
|
22
|
+
const NUMBER = /^-?\d+(\.\d+)?$/;
|
|
23
|
+
const LITERAL_KINDS = new Set(['char', 'text', 'html', 'selection', 'state', 'date']);
|
|
24
|
+
const NUMERIC_KINDS = new Set(['integer', 'float', 'decimal']);
|
|
25
|
+
/**
|
|
26
|
+
* The database-level `DEFAULT` of a column (feedback #3), in the form PostgreSQL's catalog shows it once casts are
|
|
27
|
+
* stripped, so the migrator's diff is stable: `true` / `false`, unquoted non-negative numbers, quoted strings,
|
|
28
|
+
* `now()` for the timestamps. `null` when the default is a function, the field is translated, encrypted, numbered,
|
|
29
|
+
* computed, or a relation: those stay in the ORM.
|
|
30
|
+
*/
|
|
31
|
+
export function columnDefault(key, field) {
|
|
32
|
+
if (key === 'createdAt' || key === 'updatedAt')
|
|
33
|
+
return 'now()';
|
|
34
|
+
if (field.companyDependent)
|
|
35
|
+
return "'{}'"; // per-company values; the field default applies when reading
|
|
36
|
+
const value = field.default;
|
|
37
|
+
if (value === undefined || value === null || typeof value === 'function')
|
|
38
|
+
return null;
|
|
39
|
+
if (field.translate || field.encrypted || field.sequence !== undefined || field.computed)
|
|
40
|
+
return null;
|
|
41
|
+
if (field.kind === 'boolean')
|
|
42
|
+
return typeof value === 'boolean' ? String(value) : null;
|
|
43
|
+
if (NUMERIC_KINDS.has(field.kind)) {
|
|
44
|
+
const text = typeof value === 'number' && Number.isFinite(value)
|
|
45
|
+
? String(value)
|
|
46
|
+
: typeof value === 'string'
|
|
47
|
+
? value
|
|
48
|
+
: null;
|
|
49
|
+
// Negative constants come back as `'-1'::integer`: keep them in the ORM rather than fight the catalog.
|
|
50
|
+
return text !== null && NUMBER.test(text) && !text.startsWith('-') ? text : null;
|
|
51
|
+
}
|
|
52
|
+
if (LITERAL_KINDS.has(field.kind) && typeof value === 'string')
|
|
53
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
function columnDdl(model, key, field, column) {
|
|
57
|
+
const parts = [ident(column)];
|
|
58
|
+
if (key === 'id') {
|
|
59
|
+
// A partitioned table's primary key includes the partition key (RFC 0015 §7.2): declared at table level.
|
|
60
|
+
parts.push(model.partition === undefined
|
|
61
|
+
? 'bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY'
|
|
62
|
+
: 'bigint GENERATED ALWAYS AS IDENTITY');
|
|
63
|
+
return parts.join(' ');
|
|
64
|
+
}
|
|
65
|
+
parts.push(typeName(field, model.name, key));
|
|
66
|
+
if (field.required && !field.computed)
|
|
67
|
+
parts.push('NOT NULL'); // stored computes are filled after insert (RFC 0008 §7.6)
|
|
68
|
+
const dbDefault = columnDefault(key, field);
|
|
69
|
+
if (dbDefault !== null)
|
|
70
|
+
parts.push(`DEFAULT ${dbDefault}`);
|
|
71
|
+
return parts.join(' ');
|
|
72
|
+
}
|
|
73
|
+
/** The history table of a model with `history: true` (RFC 0018 §7.4). */
|
|
74
|
+
export function historyTable(model) {
|
|
75
|
+
return `${model.table}_history`.slice(0, 63);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The history trigger of a model: archives the row as it was before its first change in each transaction (and before
|
|
79
|
+
* a delete) with its validity range, and keeps `updated_at` at the transaction time on every update, so raw SQL
|
|
80
|
+
* writes are versioned too. Idempotent: run after migrations.
|
|
81
|
+
*/
|
|
82
|
+
export function historyStatements(registry) {
|
|
83
|
+
const out = [];
|
|
84
|
+
for (const { model } of registry.models.values()) {
|
|
85
|
+
if (!model.history)
|
|
86
|
+
continue;
|
|
87
|
+
const t = ident(model.table);
|
|
88
|
+
const h = ident(historyTable(model));
|
|
89
|
+
const fn = ident(`shutro_history_${model.table}`.slice(0, 63));
|
|
90
|
+
const trigger = ident(`${model.table}_history_trg`.slice(0, 63));
|
|
91
|
+
out.push(`CREATE OR REPLACE FUNCTION ${fn}() RETURNS trigger LANGUAGE plpgsql AS $fn$
|
|
92
|
+
BEGIN
|
|
93
|
+
IF TG_OP = 'UPDATE' THEN NEW.updated_at := now(); END IF;
|
|
94
|
+
-- Versions changed again in the same transaction were never visible to anyone: archive the first one only.
|
|
95
|
+
IF OLD.updated_at IS DISTINCT FROM now() THEN
|
|
96
|
+
INSERT INTO ${h} SELECT (jsonb_populate_record(NULL::${h}, to_jsonb(OLD) || jsonb_build_object('valid_from', OLD.updated_at, 'valid_to', now()))).* ON CONFLICT DO NOTHING;
|
|
97
|
+
END IF;
|
|
98
|
+
IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
|
|
99
|
+
RETURN NEW;
|
|
100
|
+
END $fn$`, `DROP TRIGGER IF EXISTS ${trigger} ON ${t}`, `CREATE TRIGGER ${trigger} BEFORE UPDATE OR DELETE ON ${t} FOR EACH ROW EXECUTE FUNCTION ${fn}()`);
|
|
101
|
+
}
|
|
102
|
+
return out.map((text) => ({ text, params: [] }));
|
|
103
|
+
}
|
|
104
|
+
const ON_DELETE = {
|
|
105
|
+
restrict: 'RESTRICT',
|
|
106
|
+
cascade: 'CASCADE',
|
|
107
|
+
'set null': 'SET NULL',
|
|
108
|
+
};
|
|
109
|
+
/**
|
|
110
|
+
* `CREATE TABLE` statements for every model in the registry, then `ALTER TABLE … ADD FOREIGN KEY` for every
|
|
111
|
+
* many2one, then junction tables for many2many fields. Execute them in order.
|
|
112
|
+
*/
|
|
113
|
+
export function createTableStatements(registry) {
|
|
114
|
+
const tables = [];
|
|
115
|
+
const foreignKeys = [];
|
|
116
|
+
const constraints = [];
|
|
117
|
+
const junctions = new Map();
|
|
118
|
+
for (const { model } of registry.models.values()) {
|
|
119
|
+
const columns = [];
|
|
120
|
+
for (const [key, field] of Object.entries(model.fields)) {
|
|
121
|
+
const column = model.columns[key];
|
|
122
|
+
if (column === undefined) {
|
|
123
|
+
if (field.kind === 'many2many') {
|
|
124
|
+
const target = registry.get(targetOf(field) ?? '').model;
|
|
125
|
+
const junction = junctionTable(model, field, target);
|
|
126
|
+
junctions.set(junction.table, junction);
|
|
127
|
+
}
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
columns.push(columnDdl(model, key, field, column));
|
|
131
|
+
if (field.kind === 'many2one' &&
|
|
132
|
+
field.foreignKey !== false &&
|
|
133
|
+
!field.companyDependent) {
|
|
134
|
+
const target = registry.get(targetOf(field) ?? '').model;
|
|
135
|
+
const onDelete = ON_DELETE[field.ondelete] ?? 'RESTRICT';
|
|
136
|
+
foreignKeys.push(`ALTER TABLE ${ident(model.table)} ADD CONSTRAINT ${ident(`${model.table}_${column}_fkey`)} FOREIGN KEY (${ident(column)}) REFERENCES ${ident(target.table)} (${ident('id')}) ON DELETE ${onDelete}`);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (model.partition !== undefined) {
|
|
140
|
+
const keyColumn = model.columns[model.partition.key] ?? '';
|
|
141
|
+
columns.push(`PRIMARY KEY (${ident('id')}, ${ident(keyColumn)})`);
|
|
142
|
+
tables.push(`CREATE TABLE ${ident(model.table)} (${columns.join(', ')}) PARTITION BY ${model.partition.by.toUpperCase()} (${ident(keyColumn)})`);
|
|
143
|
+
}
|
|
144
|
+
else
|
|
145
|
+
tables.push(`CREATE TABLE ${ident(model.table)} (${columns.join(', ')})`);
|
|
146
|
+
// Declared SQL constraints (partial uniques are indexes and belong to the migrator).
|
|
147
|
+
for (const c of model.sqlConstraints) {
|
|
148
|
+
if (c.kind === 'unique' && c.where === undefined) {
|
|
149
|
+
constraints.push(`ALTER TABLE ${ident(model.table)} ADD CONSTRAINT ${ident(c.name)} UNIQUE (${c.columns.map((col) => ident(col)).join(', ')})`);
|
|
150
|
+
}
|
|
151
|
+
else if (c.check !== undefined) {
|
|
152
|
+
const compiled = compile(c.check);
|
|
153
|
+
if (compiled.params.length > 0) {
|
|
154
|
+
throw new InvalidModelError(model.name, `check constraint '${c.key}' contains ${compiled.params.length} parameter(s).`, 'DDL cannot take bind parameters: write the expression with literals only, e.g. sql`amount >= 0`.');
|
|
155
|
+
}
|
|
156
|
+
constraints.push(`ALTER TABLE ${ident(model.table)} ADD CONSTRAINT ${ident(c.name)} CHECK (${compiled.text})`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const junctionDdl = [...junctions.values()].map((j) => `CREATE TABLE ${ident(j.table)} (${ident(j.sourceColumn)} bigint NOT NULL REFERENCES ${ident(j.sourceTable)} (${ident('id')}) ON DELETE CASCADE, ${ident(j.targetColumn)} bigint NOT NULL REFERENCES ${ident(j.targetTable)} (${ident('id')}) ON DELETE CASCADE, PRIMARY KEY (${ident(j.sourceColumn)}, ${ident(j.targetColumn)}))`);
|
|
161
|
+
for (const { model } of registry.models.values()) {
|
|
162
|
+
if (!model.history)
|
|
163
|
+
continue;
|
|
164
|
+
const cols = Object.entries(model.columns)
|
|
165
|
+
.filter((entry) => entry[1] !== undefined)
|
|
166
|
+
.map(([key, column]) => {
|
|
167
|
+
const field = model.fields[key];
|
|
168
|
+
return `${ident(column)} ${key === 'id' ? 'bigint NOT NULL' : field.kind === 'many2one' && !field.companyDependent ? 'bigint' : typeName(field, model.name, key)}`;
|
|
169
|
+
});
|
|
170
|
+
tables.push(`CREATE TABLE ${ident(historyTable(model))} (${[...cols, '"valid_from" timestamp with time zone NOT NULL', '"valid_to" timestamp with time zone NOT NULL', 'PRIMARY KEY ("id", "valid_to")'].join(', ')})`);
|
|
171
|
+
}
|
|
172
|
+
const history = historyStatements(registry).map((c) => c.text);
|
|
173
|
+
return [...tables, ...foreignKeys, ...constraints, ...junctionDdl, ...history].map((text) => Object.freeze({ text, params: Object.freeze([]) }));
|
|
174
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `extendModel()` (RFC 0002 §7.2–7.3): a module's contribution to a model owned by a dependency. Extensions are
|
|
3
|
+
* plain data; the registry applies them in load order and enforces the view-safety rules.
|
|
4
|
+
*/
|
|
5
|
+
import type { AccessSpec, FieldGroupsInput, RuleSpec } from '../../security/index.js';
|
|
6
|
+
import { type IndexKind, type StateSpec, type Transition } from '../model/field.js';
|
|
7
|
+
import { type ConstraintSpec, type FieldsRecord, type IndexSpec, type MethodsRecord, type OnchangeFn, type SqlCheckConstraint, type SqlUniqueConstraint } from '../model/model.js';
|
|
8
|
+
/**
|
|
9
|
+
* An override layer: receives the previous implementation as `next` (bound to `this`), then the call's arguments.
|
|
10
|
+
* Parameters are `never` so that any typed implementation is accepted; `shutro generate` will type `next` exactly.
|
|
11
|
+
*/
|
|
12
|
+
export type OverrideFn = (this: unknown, next: never, ...args: never[]) => unknown;
|
|
13
|
+
/** A `replace()`d implementation: the previous layers are dropped (reported by the inspector). */
|
|
14
|
+
export interface Replacement {
|
|
15
|
+
readonly '~replace': true;
|
|
16
|
+
readonly fn: (this: unknown, ...args: never[]) => unknown;
|
|
17
|
+
}
|
|
18
|
+
/** Marks an override that intentionally does not call `next` (RFC 0002 §7.3). */
|
|
19
|
+
export declare function replace(fn: (this: unknown, ...args: never[]) => unknown): Replacement;
|
|
20
|
+
/** Changes an extension may make to an existing field (RFC 0002 §7.5 S2–S6). */
|
|
21
|
+
export interface FieldOverride {
|
|
22
|
+
readonly label?: string;
|
|
23
|
+
readonly help?: string;
|
|
24
|
+
readonly default?: unknown;
|
|
25
|
+
readonly index?: IndexKind;
|
|
26
|
+
readonly tracking?: boolean;
|
|
27
|
+
readonly copy?: boolean;
|
|
28
|
+
readonly groups?: FieldGroupsInput;
|
|
29
|
+
/** May only tighten (`true`), and then needs a default (here or on the field). */
|
|
30
|
+
readonly required?: boolean;
|
|
31
|
+
/** New values for an `extensible` selection or state. */
|
|
32
|
+
readonly selectionAdd?: Readonly<Record<string, string>>;
|
|
33
|
+
/** New states of an `extensible` state field (RFC 0010 §7.4). */
|
|
34
|
+
readonly statesAdd?: Readonly<Record<string, string | StateSpec>>;
|
|
35
|
+
/** New transitions of an `extensible` state field; existing ones are never changed. */
|
|
36
|
+
readonly transitionsAdd?: Readonly<Record<string, Transition<string>>>;
|
|
37
|
+
}
|
|
38
|
+
/** The argument of {@link extendModel} after the model name. */
|
|
39
|
+
export interface ExtensionDefinition<Fs extends FieldsRecord, Ms extends MethodsRecord> {
|
|
40
|
+
/** New fields. Required ones need a default or a compute (S1). */
|
|
41
|
+
readonly fields?: Fs;
|
|
42
|
+
readonly fieldOverrides?: Readonly<Record<string, FieldOverride>>;
|
|
43
|
+
/** New methods (an existing name is a conflict: use `overrides`). */
|
|
44
|
+
readonly methods?: Ms;
|
|
45
|
+
/** Wrappers of existing methods, receiving `next`. */
|
|
46
|
+
readonly overrides?: Readonly<Record<string, OverrideFn | Replacement>>;
|
|
47
|
+
readonly constraints?: Readonly<Record<string, ConstraintSpec>>;
|
|
48
|
+
/** Onchange handlers for fields without one (an existing key is a conflict). */
|
|
49
|
+
readonly onchange?: Readonly<Record<string, OnchangeFn>>;
|
|
50
|
+
/** Permissions to add (never removed). */
|
|
51
|
+
readonly access?: AccessSpec;
|
|
52
|
+
/** Record rules to add (an existing key is a conflict). */
|
|
53
|
+
readonly rules?: Readonly<Record<string, RuleSpec>>;
|
|
54
|
+
readonly sqlConstraints?: Readonly<Record<string, SqlUniqueConstraint<string> | SqlCheckConstraint>>;
|
|
55
|
+
readonly indexes?: readonly IndexSpec<string>[];
|
|
56
|
+
readonly tracking?: readonly string[];
|
|
57
|
+
}
|
|
58
|
+
/** An extension as `extendModel` returns it. `fields` / `methods` carry types for the registry's schema view. */
|
|
59
|
+
export interface Extension<N extends string = string, Fs extends FieldsRecord = FieldsRecord, Ms extends MethodsRecord = MethodsRecord> {
|
|
60
|
+
readonly '~extension': true;
|
|
61
|
+
readonly name: N;
|
|
62
|
+
readonly fields: Fs;
|
|
63
|
+
readonly fieldOverrides: Readonly<Record<string, FieldOverride>>;
|
|
64
|
+
readonly methods: Ms;
|
|
65
|
+
readonly overrides: Readonly<Record<string, {
|
|
66
|
+
readonly kind: 'override' | 'replace';
|
|
67
|
+
readonly fn: OverrideFn;
|
|
68
|
+
}>>;
|
|
69
|
+
readonly constraints: Readonly<Record<string, ConstraintSpec>>;
|
|
70
|
+
readonly onchange: Readonly<Record<string, OnchangeFn>>;
|
|
71
|
+
readonly access: AccessSpec;
|
|
72
|
+
readonly rules: Readonly<Record<string, RuleSpec>>;
|
|
73
|
+
readonly sqlConstraints: Readonly<Record<string, SqlUniqueConstraint<string> | SqlCheckConstraint>>;
|
|
74
|
+
readonly indexes: readonly IndexSpec<string>[];
|
|
75
|
+
readonly tracking: readonly string[];
|
|
76
|
+
}
|
|
77
|
+
/** Any extension. */
|
|
78
|
+
export type AnyExtension = Extension<string, FieldsRecord, MethodsRecord>;
|
|
79
|
+
/** True when `value` was produced by {@link extendModel}. */
|
|
80
|
+
export declare function isExtension(value: unknown): value is AnyExtension;
|
|
81
|
+
/**
|
|
82
|
+
* Declares an extension of model `name` (owned by a module this module depends on).
|
|
83
|
+
*
|
|
84
|
+
* @example
|
|
85
|
+
* ```ts
|
|
86
|
+
* export const SaleOrderStock = extendModel('sale.order', {
|
|
87
|
+
* fields: { warehouse: f.many2one('stock.warehouse', { required: true, default: (env) => ... }) },
|
|
88
|
+
* overrides: { async confirm(next): Promise<void> { await next(); await this.createPickings(); } },
|
|
89
|
+
* });
|
|
90
|
+
* ```
|
|
91
|
+
* @throws {InvalidExtensionError} for a bad model name, non-camelCase or reserved keys, non-descriptor fields, or
|
|
92
|
+
* overrides that aren't functions / `replace()` markers.
|
|
93
|
+
*/
|
|
94
|
+
export declare function extendModel<const N extends string, const Fs extends FieldsRecord = Record<never, never>, const Ms extends MethodsRecord = Record<never, never>>(name: N, definition: ExtensionDefinition<Fs, Ms>): Extension<N, Fs, Ms>;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { InvalidExtensionError } from '../errors.js';
|
|
2
|
+
import { isField, } from '../model/field.js';
|
|
3
|
+
import { RESERVED_KEYS, } from '../model/model.js';
|
|
4
|
+
/** Marks an override that intentionally does not call `next` (RFC 0002 §7.3). */
|
|
5
|
+
export function replace(fn) {
|
|
6
|
+
if (typeof fn !== 'function') {
|
|
7
|
+
throw new InvalidExtensionError('replace() expects a function.', 'Pass the new implementation: replace(function () { ... }).');
|
|
8
|
+
}
|
|
9
|
+
return Object.freeze({ '~replace': true, fn });
|
|
10
|
+
}
|
|
11
|
+
const MODEL_NAME = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$/;
|
|
12
|
+
const KEY = /^[a-z][a-zA-Z0-9]*$/;
|
|
13
|
+
const extensions = new WeakSet();
|
|
14
|
+
/** True when `value` was produced by {@link extendModel}. */
|
|
15
|
+
export function isExtension(value) {
|
|
16
|
+
return typeof value === 'object' && value !== null && extensions.has(value);
|
|
17
|
+
}
|
|
18
|
+
function isReplacement(value) {
|
|
19
|
+
return (typeof value === 'object' &&
|
|
20
|
+
value !== null &&
|
|
21
|
+
value['~replace'] === true);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Declares an extension of model `name` (owned by a module this module depends on).
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```ts
|
|
28
|
+
* export const SaleOrderStock = extendModel('sale.order', {
|
|
29
|
+
* fields: { warehouse: f.many2one('stock.warehouse', { required: true, default: (env) => ... }) },
|
|
30
|
+
* overrides: { async confirm(next): Promise<void> { await next(); await this.createPickings(); } },
|
|
31
|
+
* });
|
|
32
|
+
* ```
|
|
33
|
+
* @throws {InvalidExtensionError} for a bad model name, non-camelCase or reserved keys, non-descriptor fields, or
|
|
34
|
+
* overrides that aren't functions / `replace()` markers.
|
|
35
|
+
*/
|
|
36
|
+
export function extendModel(name, definition) {
|
|
37
|
+
if (typeof name !== 'string' || !MODEL_NAME.test(name)) {
|
|
38
|
+
throw new InvalidExtensionError(`${JSON.stringify(name)} is not a valid model name.`, "Use the model's dotted name, e.g. extendModel('sale.order', { ... }).");
|
|
39
|
+
}
|
|
40
|
+
const fields = definition.fields ?? {};
|
|
41
|
+
for (const [key, field] of Object.entries(fields)) {
|
|
42
|
+
if (!KEY.test(key))
|
|
43
|
+
throw new InvalidExtensionError(`Extension of '${name}': field key '${key}' is not camelCase.`, "Use keys like 'deliveryDate'.");
|
|
44
|
+
if (RESERVED_KEYS.includes(key))
|
|
45
|
+
throw new InvalidExtensionError(`Extension of '${name}': '${key}' is a reserved field name.`, 'Rename the field.');
|
|
46
|
+
if (!isField(field))
|
|
47
|
+
throw new InvalidExtensionError(`Extension of '${name}': field '${key}' is not a descriptor made by f.*.`, 'Build fields with f.char(), f.many2one(), …');
|
|
48
|
+
}
|
|
49
|
+
const methods = definition.methods ?? {};
|
|
50
|
+
for (const [key, fn] of Object.entries(methods)) {
|
|
51
|
+
if (!KEY.test(key) || RESERVED_KEYS.includes(key))
|
|
52
|
+
throw new InvalidExtensionError(`Extension of '${name}': method name '${key}' is invalid or reserved.`, "Use names like 'createPickings'.");
|
|
53
|
+
if (typeof fn !== 'function')
|
|
54
|
+
throw new InvalidExtensionError(`Extension of '${name}': method '${key}' is not a function.`, 'Methods are functions taking a recordset.');
|
|
55
|
+
}
|
|
56
|
+
const overrides = {};
|
|
57
|
+
for (const [key, value] of Object.entries(definition.overrides ?? {})) {
|
|
58
|
+
if (!KEY.test(key))
|
|
59
|
+
throw new InvalidExtensionError(`Extension of '${name}': override name '${key}' is not camelCase.`, 'Name the method being overridden.');
|
|
60
|
+
if (isReplacement(value))
|
|
61
|
+
overrides[key] = { kind: 'replace', fn: value.fn };
|
|
62
|
+
else if (typeof value === 'function')
|
|
63
|
+
overrides[key] = { kind: 'override', fn: value };
|
|
64
|
+
else
|
|
65
|
+
throw new InvalidExtensionError(`Extension of '${name}': override '${key}' is not a function.`, 'Write overrides: { confirm(next, ...args) { ...; return next(...args); } } or replace(fn).');
|
|
66
|
+
}
|
|
67
|
+
for (const [key, override] of Object.entries(definition.fieldOverrides ?? {})) {
|
|
68
|
+
if (!KEY.test(key))
|
|
69
|
+
throw new InvalidExtensionError(`Extension of '${name}': fieldOverrides key '${key}' is not camelCase.`, 'Name the field being changed.');
|
|
70
|
+
if (typeof override !== 'object' || override === null)
|
|
71
|
+
throw new InvalidExtensionError(`Extension of '${name}': fieldOverrides.${key} must be an object.`, "E.g. { label: 'Reference', required: true, default: 'x' }.");
|
|
72
|
+
}
|
|
73
|
+
const extension = Object.freeze({
|
|
74
|
+
'~extension': true,
|
|
75
|
+
name,
|
|
76
|
+
fields: Object.freeze({ ...fields }),
|
|
77
|
+
fieldOverrides: Object.freeze({ ...(definition.fieldOverrides ?? {}) }),
|
|
78
|
+
methods: Object.freeze({ ...methods }),
|
|
79
|
+
overrides: Object.freeze(overrides),
|
|
80
|
+
constraints: Object.freeze({ ...(definition.constraints ?? {}) }),
|
|
81
|
+
onchange: Object.freeze({ ...(definition.onchange ?? {}) }),
|
|
82
|
+
access: Object.freeze({ ...(definition.access ?? {}) }),
|
|
83
|
+
rules: Object.freeze({ ...(definition.rules ?? {}) }),
|
|
84
|
+
sqlConstraints: Object.freeze({ ...(definition.sqlConstraints ?? {}) }),
|
|
85
|
+
indexes: Object.freeze([...(definition.indexes ?? [])]),
|
|
86
|
+
tracking: Object.freeze([...(definition.tracking ?? [])]),
|
|
87
|
+
});
|
|
88
|
+
extensions.add(extension);
|
|
89
|
+
return extension;
|
|
90
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `defineModule()` (RFC 0002 §7.1): a named, versioned unit that depends on other modules (by object, so a
|
|
3
|
+
* dependency cycle can't even be written), owns models and extends models of its dependencies. The module type
|
|
4
|
+
* carries its models, extensions and dependencies, so a registry built from modules knows every model it contains
|
|
5
|
+
* (until `shutro generate` emits the same view).
|
|
6
|
+
*/
|
|
7
|
+
import type { GroupDefinition, PermissionDefinition } from '../../security/index.js';
|
|
8
|
+
import type { SequenceDefinition } from '../../sequence/index.js';
|
|
9
|
+
import type { DataRecord } from '../data/data.js';
|
|
10
|
+
import { type AnyModel } from '../model/model.js';
|
|
11
|
+
import { type AnyExtension } from './extension.js';
|
|
12
|
+
import type { Registry } from './registry.js';
|
|
13
|
+
/** What a data-migration hook receives: raw SQL on the migration transaction, and the registry. */
|
|
14
|
+
export interface MigrationContext {
|
|
15
|
+
sql<R extends Record<string, unknown> = Record<string, unknown>>(strings: TemplateStringsArray, ...values: readonly unknown[]): Promise<readonly R[]>;
|
|
16
|
+
readonly registry: Registry;
|
|
17
|
+
}
|
|
18
|
+
/** A per-module data migration: runs once when the module is upgraded past `version` (never on a fresh install). */
|
|
19
|
+
export interface DataMigration {
|
|
20
|
+
/** `major.minor.patch`; must not exceed the module's version. */
|
|
21
|
+
readonly version: string;
|
|
22
|
+
readonly description?: string;
|
|
23
|
+
readonly up: (ctx: MigrationContext) => Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
/** A module without the type parameters that carry its models and dependencies. */
|
|
26
|
+
export interface ModuleBase {
|
|
27
|
+
readonly name: string;
|
|
28
|
+
readonly version: string;
|
|
29
|
+
readonly label: string;
|
|
30
|
+
readonly depends: readonly ModuleBase[];
|
|
31
|
+
readonly models: readonly AnyModel[];
|
|
32
|
+
readonly extensions: readonly AnyExtension[];
|
|
33
|
+
/** Data-migration hooks, sorted by version. */
|
|
34
|
+
readonly migrations: readonly DataMigration[];
|
|
35
|
+
/** Document sequences this module declares (RFC 0012 §7.1). */
|
|
36
|
+
readonly sequences: readonly SequenceDefinition[];
|
|
37
|
+
/** Security groups this module declares (RFC 0014 §7.1). */
|
|
38
|
+
readonly groups: readonly GroupDefinition[];
|
|
39
|
+
/** Feature permissions this module declares (RFC 0014 §7.9). */
|
|
40
|
+
readonly permissions: readonly PermissionDefinition[];
|
|
41
|
+
/** Records the module ships (RFC 0017), in load order. */
|
|
42
|
+
readonly data: readonly DataRecord[];
|
|
43
|
+
}
|
|
44
|
+
/** A module as `defineModule` returns it; the type parameters carry the model types for the registry's schema view. */
|
|
45
|
+
export interface Module<Ms extends readonly AnyModel[] = readonly AnyModel[], Deps extends readonly ModuleBase[] = readonly ModuleBase[], Exts extends readonly AnyExtension[] = readonly AnyExtension[]> extends ModuleBase {
|
|
46
|
+
readonly depends: Deps;
|
|
47
|
+
readonly models: Ms;
|
|
48
|
+
readonly extensions: Exts;
|
|
49
|
+
}
|
|
50
|
+
/** The argument of {@link defineModule}. */
|
|
51
|
+
export interface ModuleDefinition<Ms extends readonly AnyModel[], Deps extends readonly ModuleBase[], Exts extends readonly AnyExtension[]> {
|
|
52
|
+
/** Unique, snake_case, stable (stored in the database for migrations). */
|
|
53
|
+
readonly name: string;
|
|
54
|
+
/** `major.minor.patch`. Defaults to `0.0.0`. */
|
|
55
|
+
readonly version?: string;
|
|
56
|
+
/** Human label; defaults to the humanized name. */
|
|
57
|
+
readonly label?: string;
|
|
58
|
+
/** Direct dependencies, as module objects. Transitive ones are collected by the registry. */
|
|
59
|
+
readonly depends?: Deps;
|
|
60
|
+
/** Models this module owns. */
|
|
61
|
+
readonly models: Ms;
|
|
62
|
+
/** Extensions of models owned by (transitive) dependencies. */
|
|
63
|
+
readonly extensions?: Exts;
|
|
64
|
+
/** Data-migration hooks (see {@link DataMigration}). */
|
|
65
|
+
readonly migrations?: readonly DataMigration[];
|
|
66
|
+
/** Document sequences (`defineSequence`). */
|
|
67
|
+
readonly sequences?: readonly SequenceDefinition[];
|
|
68
|
+
/** Security groups (`defineGroup`). */
|
|
69
|
+
readonly groups?: readonly GroupDefinition[];
|
|
70
|
+
/** Feature permissions (`definePermission`): apps, menus, buttons, approvals. */
|
|
71
|
+
readonly permissions?: readonly PermissionDefinition[];
|
|
72
|
+
/** Records the module ships (`record`, `override`; RFC 0017), loaded in this order by `shutro migrate apply`. */
|
|
73
|
+
readonly data?: readonly DataRecord[];
|
|
74
|
+
}
|
|
75
|
+
/** Numeric comparison of `major.minor.patch` versions. */
|
|
76
|
+
export declare function compareVersions(a: string, b: string): number;
|
|
77
|
+
/** True when `value` was produced by {@link defineModule}. */
|
|
78
|
+
export declare function isModule(value: unknown): value is Module;
|
|
79
|
+
/**
|
|
80
|
+
* Defines a module.
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* ```ts
|
|
84
|
+
* export default defineModule({ name: 'sale_stock', depends: [sale, stock], models: [], extensions: [SaleOrderStock] });
|
|
85
|
+
* ```
|
|
86
|
+
* @throws {InvalidModuleError} for a bad name or version, or `depends` / `models` / `extensions` entries of the wrong kind.
|
|
87
|
+
* @throws {DuplicateModelError} when two models in the list share a name.
|
|
88
|
+
*/
|
|
89
|
+
export declare function defineModule<const Ms extends readonly AnyModel[], const Deps extends readonly ModuleBase[] = readonly [], const Exts extends readonly AnyExtension[] = readonly []>(definition: ModuleDefinition<Ms, Deps, Exts>): Module<Ms, Deps, Exts>;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `defineModule()` (RFC 0002 §7.1): a named, versioned unit that depends on other modules (by object, so a
|
|
3
|
+
* dependency cycle can't even be written), owns models and extends models of its dependencies. The module type
|
|
4
|
+
* carries its models, extensions and dependencies, so a registry built from modules knows every model it contains
|
|
5
|
+
* (until `shutro generate` emits the same view).
|
|
6
|
+
*/
|
|
7
|
+
import { DuplicateModelError, InvalidModuleError } from '../errors.js';
|
|
8
|
+
import { humanize, isModel } from '../model/model.js';
|
|
9
|
+
import { isExtension } from './extension.js';
|
|
10
|
+
const MODULE_NAME = /^[a-z][a-z0-9_]*$/;
|
|
11
|
+
const VERSION = /^\d+\.\d+\.\d+$/;
|
|
12
|
+
const modules = new WeakSet();
|
|
13
|
+
/** Numeric comparison of `major.minor.patch` versions. */
|
|
14
|
+
export function compareVersions(a, b) {
|
|
15
|
+
const pa = a.split('.').map(Number);
|
|
16
|
+
const pb = b.split('.').map(Number);
|
|
17
|
+
for (let i = 0; i < 3; i++) {
|
|
18
|
+
const d = (pa[i] ?? 0) - (pb[i] ?? 0);
|
|
19
|
+
if (d !== 0)
|
|
20
|
+
return d;
|
|
21
|
+
}
|
|
22
|
+
return 0;
|
|
23
|
+
}
|
|
24
|
+
/** True when `value` was produced by {@link defineModule}. */
|
|
25
|
+
export function isModule(value) {
|
|
26
|
+
return typeof value === 'object' && value !== null && modules.has(value);
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Defines a module.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```ts
|
|
33
|
+
* export default defineModule({ name: 'sale_stock', depends: [sale, stock], models: [], extensions: [SaleOrderStock] });
|
|
34
|
+
* ```
|
|
35
|
+
* @throws {InvalidModuleError} for a bad name or version, or `depends` / `models` / `extensions` entries of the wrong kind.
|
|
36
|
+
* @throws {DuplicateModelError} when two models in the list share a name.
|
|
37
|
+
*/
|
|
38
|
+
export function defineModule(definition) {
|
|
39
|
+
const { name } = definition;
|
|
40
|
+
if (typeof name !== 'string' || !MODULE_NAME.test(name)) {
|
|
41
|
+
throw new InvalidModuleError(`${JSON.stringify(name)} is not a valid module name.`, "Use lower-case snake_case such as 'sale_stock'; the name is stored in the database, so keep it stable.");
|
|
42
|
+
}
|
|
43
|
+
const version = definition.version ?? '0.0.0';
|
|
44
|
+
if (!VERSION.test(version)) {
|
|
45
|
+
throw new InvalidModuleError(`Module '${name}' has version ${JSON.stringify(version)}.`, "Use 'major.minor.patch', e.g. '1.0.0'.");
|
|
46
|
+
}
|
|
47
|
+
const depends = (definition.depends ?? []);
|
|
48
|
+
depends.forEach((dep, i) => {
|
|
49
|
+
if (!isModule(dep)) {
|
|
50
|
+
throw new InvalidModuleError(`Module '${name}' depends[${i}] is not a module.`, 'Import the dependency module object (the result of defineModule) and pass it; names are not accepted, so typos are impossible.');
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
const seen = new Set();
|
|
54
|
+
definition.models.forEach((model, i) => {
|
|
55
|
+
if (!isModel(model))
|
|
56
|
+
throw new InvalidModuleError(`Module '${name}' models[${i}] is not a model.`, 'Pass the result of defineModel().');
|
|
57
|
+
if (seen.has(model.name))
|
|
58
|
+
throw new DuplicateModelError(model.name, [name, name]);
|
|
59
|
+
seen.add(model.name);
|
|
60
|
+
});
|
|
61
|
+
const extensions = (definition.extensions ?? []);
|
|
62
|
+
extensions.forEach((ext, i) => {
|
|
63
|
+
if (!isExtension(ext))
|
|
64
|
+
throw new InvalidModuleError(`Module '${name}' extensions[${i}] is not an extension.`, 'Pass the result of extendModel().');
|
|
65
|
+
if (seen.has(ext.name)) {
|
|
66
|
+
throw new InvalidModuleError(`Module '${name}' both defines and extends '${ext.name}'.`, 'Put the extension content into the model definition instead.');
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
const migrations = [...(definition.migrations ?? [])];
|
|
70
|
+
for (const m of migrations) {
|
|
71
|
+
if (!VERSION.test(m.version))
|
|
72
|
+
throw new InvalidModuleError(`Module '${name}' has a migration with version ${JSON.stringify(m.version)}.`, "Use 'major.minor.patch'.");
|
|
73
|
+
if (compareVersions(m.version, version) > 0)
|
|
74
|
+
throw new InvalidModuleError(`Module '${name}' has a migration for ${m.version}, beyond its version ${version}.`, 'Raise the module version, or lower the migration version.');
|
|
75
|
+
if (typeof m.up !== 'function')
|
|
76
|
+
throw new InvalidModuleError(`Module '${name}' migration ${m.version} has no up() function.`, 'Pass { version, up: async (ctx) => { ... } }.');
|
|
77
|
+
}
|
|
78
|
+
for (const seq of definition.sequences ?? []) {
|
|
79
|
+
if (typeof seq !== 'object' || seq === null || typeof seq.code !== 'string')
|
|
80
|
+
throw new InvalidModuleError(`Module '${name}' has a malformed sequence.`, 'Pass defineSequence({ code, ... }) entries.');
|
|
81
|
+
}
|
|
82
|
+
migrations.sort((a, b) => compareVersions(a.version, b.version));
|
|
83
|
+
const module = Object.freeze({
|
|
84
|
+
name,
|
|
85
|
+
version,
|
|
86
|
+
label: definition.label ?? humanize(name),
|
|
87
|
+
depends: Object.freeze([...depends]),
|
|
88
|
+
models: Object.freeze([...definition.models]),
|
|
89
|
+
extensions: Object.freeze([...extensions]),
|
|
90
|
+
migrations: Object.freeze(migrations),
|
|
91
|
+
sequences: Object.freeze([...(definition.sequences ?? [])]),
|
|
92
|
+
groups: Object.freeze([...(definition.groups ?? [])]),
|
|
93
|
+
permissions: Object.freeze([...(definition.permissions ?? [])]),
|
|
94
|
+
data: Object.freeze([...(definition.data ?? [])]),
|
|
95
|
+
});
|
|
96
|
+
modules.add(module);
|
|
97
|
+
return module;
|
|
98
|
+
}
|