shutro 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +99 -2
  3. package/dist/audit/index.d.ts +59 -0
  4. package/dist/audit/index.js +96 -0
  5. package/dist/cli/bin.d.ts +2 -0
  6. package/dist/cli/bin.js +11 -0
  7. package/dist/cli/cli.d.ts +10 -0
  8. package/dist/cli/cli.js +164 -0
  9. package/dist/cli/config.d.ts +18 -0
  10. package/dist/cli/config.js +49 -0
  11. package/dist/cli/errors.d.ts +16 -0
  12. package/dist/cli/errors.js +23 -0
  13. package/dist/cli/generate/generate.d.ts +33 -0
  14. package/dist/cli/generate/generate.js +84 -0
  15. package/dist/cli/generate/render.d.ts +23 -0
  16. package/dist/cli/generate/render.js +249 -0
  17. package/dist/cli/index.d.ts +12 -0
  18. package/dist/cli/index.js +12 -0
  19. package/dist/cli/init.d.ts +2 -0
  20. package/dist/cli/init.js +65 -0
  21. package/dist/cli/inspect.d.ts +10 -0
  22. package/dist/cli/inspect.js +82 -0
  23. package/dist/cli/packages.d.ts +6 -0
  24. package/dist/cli/packages.js +6 -0
  25. package/dist/cli/project.d.ts +18 -0
  26. package/dist/cli/project.js +39 -0
  27. package/dist/cli/resolve.d.ts +2 -0
  28. package/dist/cli/resolve.js +28 -0
  29. package/dist/core/compute/graph.d.ts +52 -0
  30. package/dist/core/compute/graph.js +162 -0
  31. package/dist/core/data/data.d.ts +59 -0
  32. package/dist/core/data/data.js +119 -0
  33. package/dist/core/data/load.d.ts +37 -0
  34. package/dist/core/data/load.js +236 -0
  35. package/dist/core/env/env.d.ts +468 -0
  36. package/dist/core/env/env.js +916 -0
  37. package/dist/core/env/identity.d.ts +43 -0
  38. package/dist/core/env/identity.js +65 -0
  39. package/dist/core/env/inspector.d.ts +55 -0
  40. package/dist/core/env/inspector.js +85 -0
  41. package/dist/core/env/time.d.ts +12 -0
  42. package/dist/core/env/time.js +38 -0
  43. package/dist/core/errors.d.ts +256 -0
  44. package/dist/core/errors.js +360 -0
  45. package/dist/core/events/events.d.ts +44 -0
  46. package/dist/core/events/events.js +58 -0
  47. package/dist/core/events/workers.d.ts +56 -0
  48. package/dist/core/events/workers.js +155 -0
  49. package/dist/core/index.d.ts +51 -0
  50. package/dist/core/index.js +42 -0
  51. package/dist/core/model/company.d.ts +6 -0
  52. package/dist/core/model/company.js +31 -0
  53. package/dist/core/model/faces.d.ts +42 -0
  54. package/dist/core/model/faces.js +1 -0
  55. package/dist/core/model/field.d.ts +479 -0
  56. package/dist/core/model/field.js +461 -0
  57. package/dist/core/model/generated.d.ts +77 -0
  58. package/dist/core/model/generated.js +1 -0
  59. package/dist/core/model/id.d.ts +33 -0
  60. package/dist/core/model/id.js +4 -0
  61. package/dist/core/model/model.d.ts +387 -0
  62. package/dist/core/model/model.js +566 -0
  63. package/dist/core/model/partition.d.ts +31 -0
  64. package/dist/core/model/partition.js +71 -0
  65. package/dist/core/model/related.d.ts +17 -0
  66. package/dist/core/model/related.js +60 -0
  67. package/dist/core/model/typed.d.ts +107 -0
  68. package/dist/core/model/typed.js +46 -0
  69. package/dist/core/money/currency.d.ts +39 -0
  70. package/dist/core/money/currency.js +37 -0
  71. package/dist/core/money/decimal.d.ts +26 -0
  72. package/dist/core/money/decimal.js +51 -0
  73. package/dist/core/money/fx.d.ts +68 -0
  74. package/dist/core/money/fx.js +124 -0
  75. package/dist/core/money/money.d.ts +84 -0
  76. package/dist/core/money/money.js +173 -0
  77. package/dist/core/money/quantity.d.ts +67 -0
  78. package/dist/core/money/quantity.js +108 -0
  79. package/dist/core/money/rounding.d.ts +11 -0
  80. package/dist/core/money/rounding.js +12 -0
  81. package/dist/core/recordset/aggregate.d.ts +22 -0
  82. package/dist/core/recordset/aggregate.js +258 -0
  83. package/dist/core/recordset/audit.d.ts +33 -0
  84. package/dist/core/recordset/audit.js +262 -0
  85. package/dist/core/recordset/compute.d.ts +36 -0
  86. package/dist/core/recordset/compute.js +414 -0
  87. package/dist/core/recordset/constraints.d.ts +9 -0
  88. package/dist/core/recordset/constraints.js +61 -0
  89. package/dist/core/recordset/domain.d.ts +31 -0
  90. package/dist/core/recordset/domain.js +300 -0
  91. package/dist/core/recordset/onchange.d.ts +43 -0
  92. package/dist/core/recordset/onchange.js +240 -0
  93. package/dist/core/recordset/recordset.d.ts +110 -0
  94. package/dist/core/recordset/recordset.js +789 -0
  95. package/dist/core/recordset/relations.d.ts +15 -0
  96. package/dist/core/recordset/relations.js +13 -0
  97. package/dist/core/recordset/rls.d.ts +15 -0
  98. package/dist/core/recordset/rls.js +108 -0
  99. package/dist/core/recordset/security.d.ts +56 -0
  100. package/dist/core/recordset/security.js +269 -0
  101. package/dist/core/recordset/sequences.d.ts +31 -0
  102. package/dist/core/recordset/sequences.js +154 -0
  103. package/dist/core/recordset/source.d.ts +9 -0
  104. package/dist/core/recordset/source.js +19 -0
  105. package/dist/core/recordset/sqlErrors.d.ts +6 -0
  106. package/dist/core/recordset/sqlErrors.js +39 -0
  107. package/dist/core/recordset/transitions.d.ts +10 -0
  108. package/dist/core/recordset/transitions.js +80 -0
  109. package/dist/core/recordset/types.d.ts +415 -0
  110. package/dist/core/recordset/types.js +8 -0
  111. package/dist/core/recordset/values.d.ts +33 -0
  112. package/dist/core/recordset/values.js +177 -0
  113. package/dist/core/recordset/writes.d.ts +42 -0
  114. package/dist/core/recordset/writes.js +786 -0
  115. package/dist/core/registry/ddl.d.ts +31 -0
  116. package/dist/core/registry/ddl.js +174 -0
  117. package/dist/core/registry/extension.d.ts +94 -0
  118. package/dist/core/registry/extension.js +90 -0
  119. package/dist/core/registry/module.d.ts +89 -0
  120. package/dist/core/registry/module.js +98 -0
  121. package/dist/core/registry/registry.d.ts +130 -0
  122. package/dist/core/registry/registry.js +591 -0
  123. package/dist/core/security/runtime.d.ts +102 -0
  124. package/dist/core/security/runtime.js +232 -0
  125. package/dist/driver-pg/driver.d.ts +88 -0
  126. package/dist/driver-pg/driver.js +177 -0
  127. package/dist/driver-pg/errors.d.ts +72 -0
  128. package/dist/driver-pg/errors.js +182 -0
  129. package/dist/driver-pg/index.d.ts +7 -0
  130. package/dist/driver-pg/index.js +7 -0
  131. package/dist/i18n/index.d.ts +25 -0
  132. package/dist/i18n/index.js +51 -0
  133. package/dist/migrate/apply.d.ts +78 -0
  134. package/dist/migrate/apply.js +167 -0
  135. package/dist/migrate/catalog.d.ts +10 -0
  136. package/dist/migrate/catalog.js +122 -0
  137. package/dist/migrate/diff.d.ts +98 -0
  138. package/dist/migrate/diff.js +160 -0
  139. package/dist/migrate/errors.d.ts +21 -0
  140. package/dist/migrate/errors.js +31 -0
  141. package/dist/migrate/index.d.ts +18 -0
  142. package/dist/migrate/index.js +18 -0
  143. package/dist/migrate/render.d.ts +5 -0
  144. package/dist/migrate/render.js +101 -0
  145. package/dist/migrate/schema.d.ts +61 -0
  146. package/dist/migrate/schema.js +233 -0
  147. package/dist/security/index.d.ts +147 -0
  148. package/dist/security/index.js +278 -0
  149. package/dist/sequence/index.d.ts +63 -0
  150. package/dist/sequence/index.js +106 -0
  151. package/dist/sql/ast.d.ts +49 -0
  152. package/dist/sql/ast.js +47 -0
  153. package/dist/sql/builder/builder.d.ts +215 -0
  154. package/dist/sql/builder/builder.js +308 -0
  155. package/dist/sql/builder/expression.d.ts +80 -0
  156. package/dist/sql/builder/expression.js +126 -0
  157. package/dist/sql/compile.d.ts +18 -0
  158. package/dist/sql/compile.js +41 -0
  159. package/dist/sql/errors.d.ts +13 -0
  160. package/dist/sql/errors.js +16 -0
  161. package/dist/sql/index.d.ts +19 -0
  162. package/dist/sql/index.js +19 -0
  163. package/dist/sql/tag.d.ts +47 -0
  164. package/dist/sql/tag.js +123 -0
  165. package/package.json +82 -4
@@ -0,0 +1,566 @@
1
+ /**
2
+ * `defineModel()` (RFC 0001 §7): merges implicit fields, derives names, validates everything that only needs the
3
+ * model itself (sibling references, methods, constraints), and exposes runtime metadata for Kosh.
4
+ * Cross-model checks (relation targets, `depends` paths, one2many inverses) belong to the registry (RFC 0002).
5
+ */
6
+ import { assertAccessSpec, assertRuleSpec, } from '../../security/index.js';
7
+ import { isSql } from '../../sql/index.js';
8
+ import { InvalidModelError } from '../errors.js';
9
+ import { companyConsistencyCheck } from './company.js';
10
+ import { f, implicitIdField, isField, withDefaultLabel, } from './field.js';
11
+ const TRANSITION = Symbol.for('shutro.transition');
12
+ /** The state field and transition a generated (or wrapped) method runs, if it is one (RFC 0010 §7.1). */
13
+ export function transitionOf(fn) {
14
+ return typeof fn === 'function'
15
+ ? (fn[TRANSITION] ?? undefined)
16
+ : undefined;
17
+ }
18
+ /** @internal Marks `fn` as running transition `name` of `field`. */
19
+ export function markTransition(fn, field, name) {
20
+ Object.defineProperty(fn, TRANSITION, {
21
+ value: Object.freeze({ field, name }),
22
+ enumerable: false,
23
+ });
24
+ return fn;
25
+ }
26
+ // --------------------------------------------------------------------------------------------- sibling checks
27
+ /** Keys that can't be user fields or methods: implicit fields and the recordset API (RFC 0001 §7.5). */
28
+ export const RESERVED_KEYS = Object.freeze([
29
+ 'id',
30
+ 'createdAt',
31
+ 'updatedAt',
32
+ 'createdBy',
33
+ 'updatedBy',
34
+ 'env',
35
+ 'ids',
36
+ 'model',
37
+ 'length',
38
+ 'load',
39
+ 'read',
40
+ 'write',
41
+ 'create',
42
+ 'unlink',
43
+ 'search',
44
+ 'browse',
45
+ 'exists',
46
+ 'ensureOne',
47
+ 'first',
48
+ 'filter',
49
+ 'map',
50
+ 'mapped',
51
+ 'sortedBy',
52
+ 'groupBy',
53
+ 'sum',
54
+ 'union',
55
+ 'intersect',
56
+ 'minus',
57
+ 'concat',
58
+ 'copy',
59
+ 'withEnv',
60
+ 'withCompany',
61
+ 'withLang',
62
+ 'withFlags',
63
+ 'toJSON',
64
+ 'describe',
65
+ 'equals',
66
+ 'isEmpty',
67
+ 'names',
68
+ 'modelName',
69
+ 'registered',
70
+ 'resolveIds',
71
+ 'fieldValue',
72
+ ]);
73
+ // --------------------------------------------------------------------------------------------------- helpers
74
+ const MODEL_NAME = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$/;
75
+ const FIELD_KEY = /^[a-z][a-zA-Z0-9]*$/;
76
+ const IDENTIFIER = /^[a-z_][a-z0-9_]*$/;
77
+ const MAX_IDENTIFIER = 63;
78
+ const models = new WeakSet();
79
+ /** @internal The compute of the implicit `displayName`: the engine derives it from `recName` (RFC 0008 §7.1). */
80
+ export const defaultDisplayName = () => undefined;
81
+ /** True when `value` was produced by {@link defineModel}. */
82
+ export function isModel(value) {
83
+ return typeof value === 'object' && value !== null && models.has(value);
84
+ }
85
+ /** `amountTotal` → `amount_total`. */
86
+ export function snakeCase(key) {
87
+ return key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
88
+ }
89
+ /** `amountTotal` → `Amount Total`, `sale.order` → `Sale Order`. */
90
+ export function humanize(name) {
91
+ return name
92
+ .replace(/[._]/g, ' ')
93
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
94
+ .split(' ')
95
+ .filter((w) => w !== '')
96
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
97
+ .join(' ');
98
+ }
99
+ function columnOf(key, field) {
100
+ if (!field.store)
101
+ return undefined;
102
+ if (field.column !== undefined)
103
+ return field.column;
104
+ const snake = snakeCase(key);
105
+ return field.kind === 'many2one' ? `${snake}_id` : snake;
106
+ }
107
+ function fail(model, problem, hint) {
108
+ throw new InvalidModelError(model, problem, hint);
109
+ }
110
+ function sqlName(table, suffix, model) {
111
+ const name = `${table}_${suffix}`;
112
+ if (name.length > MAX_IDENTIFIER) {
113
+ fail(model, `the PostgreSQL name '${name}' is longer than ${MAX_IDENTIFIER} characters.`, 'Use a shorter table name or constraint/index key.');
114
+ }
115
+ return name;
116
+ }
117
+ // ---------------------------------------------------------------------------------------------- defineModel
118
+ /**
119
+ * Defines a model (RFC 0001).
120
+ *
121
+ * @example
122
+ * ```ts
123
+ * export const SaleOrder = defineModel('sale.order', {
124
+ * companyScoped: { required: true },
125
+ * fields: {
126
+ * name: f.char({ required: true, readonly: true, sequence: 'sale.order' }),
127
+ * partner: f.many2one('res.partner', { required: true }),
128
+ * currency: f.many2one('res.currency', { required: true }),
129
+ * amountTotal: f.monetary({ currency: 'currency', store: true, depends: ['lines.subtotal'], compute: 'computeAmounts' }),
130
+ * },
131
+ * methods: { computeAmounts(): void { … } },
132
+ * });
133
+ * ```
134
+ * @throws {InvalidModelError} for reserved or non-camelCase keys, column collisions, a `monetary.currency` that
135
+ * isn't a `many2one('res.currency')`, a `compute` name that isn't a method, and invalid order / constraints / indexes.
136
+ */
137
+ export function defineModel(name, definition) {
138
+ if (typeof name !== 'string' || !MODEL_NAME.test(name)) {
139
+ throw new InvalidModelError(String(name), 'the model name is not a dotted lower-case identifier.', "Use names such as 'res.partner' or 'sale.order.line'.");
140
+ }
141
+ const table = definition.table ?? name.replaceAll('.', '_');
142
+ if (!IDENTIFIER.test(table) || table.length > MAX_IDENTIFIER) {
143
+ fail(name, `'${table}' is not a valid table name.`, 'Use lower-case snake_case, at most 63 characters.');
144
+ }
145
+ // --- user fields
146
+ const user = {};
147
+ for (const [key, field] of Object.entries(definition.fields)) {
148
+ if (!FIELD_KEY.test(key))
149
+ fail(name, `field key '${key}' is not camelCase.`, "Use keys like 'amountTotal'; columns become snake_case automatically.");
150
+ if (RESERVED_KEYS.includes(key) && key !== 'displayName') {
151
+ fail(name, `'${key}' is a reserved field name.`, `Rename the field; reserved: ${RESERVED_KEYS.join(', ')}.`);
152
+ }
153
+ if (!isField(field))
154
+ fail(name, `field '${key}' is not a descriptor made by f.*.`, 'Build fields with f.char(), f.many2one(), …');
155
+ user[key] = withDefaultLabel(field, humanize(key));
156
+ }
157
+ // --- implicit fields
158
+ const implicit = {
159
+ id: implicitIdField(name),
160
+ createdAt: f.datetime({ required: true, readonly: true, label: 'Created At', copy: false }),
161
+ updatedAt: f.datetime({ required: true, readonly: true, label: 'Updated At', copy: false }),
162
+ createdBy: f.many2one('res.users', {
163
+ readonly: true,
164
+ ondelete: 'set null',
165
+ label: 'Created By',
166
+ copy: false,
167
+ }),
168
+ updatedBy: f.many2one('res.users', {
169
+ readonly: true,
170
+ ondelete: 'set null',
171
+ label: 'Updated By',
172
+ copy: false,
173
+ }),
174
+ displayName: user['displayName'] ??
175
+ f.char({ required: true, label: 'Display Name', compute: defaultDisplayName, copy: false }),
176
+ };
177
+ if (definition.archivable === true)
178
+ implicit['active'] = f.boolean({ default: true, label: 'Active' });
179
+ if (definition.companyScoped !== undefined) {
180
+ implicit['company'] = f.many2one('res.company', {
181
+ required: definition.companyScoped.required,
182
+ label: 'Company',
183
+ index: true,
184
+ default: (env) => env.companyId,
185
+ });
186
+ }
187
+ const fields = { ...implicit };
188
+ for (const [key, field] of Object.entries(user))
189
+ if (key !== 'displayName')
190
+ fields[key] = field;
191
+ const keys = Object.keys(fields);
192
+ const has = (key) => Object.hasOwn(fields, key);
193
+ // --- columns
194
+ const columns = {};
195
+ const seen = new Map();
196
+ for (const [key, field] of Object.entries(fields)) {
197
+ const column = columnOf(key, field);
198
+ columns[key] = column;
199
+ if (column === undefined)
200
+ continue;
201
+ const other = seen.get(column);
202
+ if (other !== undefined) {
203
+ fail(name, `fields '${other}' and '${key}' both map to column '${column}'.`, 'Rename one of them, or set `column` explicitly on one.');
204
+ }
205
+ seen.set(column, key);
206
+ }
207
+ // --- methods
208
+ const methods = { ...(definition.methods ?? {}) };
209
+ for (const [key, fn] of Object.entries(methods)) {
210
+ if (!FIELD_KEY.test(key))
211
+ fail(name, `method name '${key}' is not camelCase.`, "Use names like 'computeAmounts'.");
212
+ if (RESERVED_KEYS.includes(key))
213
+ fail(name, `'${key}' is a reserved method name.`, 'Rename the method; it would shadow the recordset API.');
214
+ if (typeof fn !== 'function')
215
+ fail(name, `method '${key}' is not a function.`, 'Methods are functions taking a recordset.');
216
+ }
217
+ // --- sibling references
218
+ const expectTarget = (key, ref, target, option) => {
219
+ const sibling = fields[ref];
220
+ if (sibling === undefined ||
221
+ sibling.kind !== 'many2one' ||
222
+ sibling.target !== target) {
223
+ fail(name, `field '${key}' has ${option}: '${ref}', which is not a many2one('${target}') field of this model.`, `Point ${option} at a sibling field declared as f.many2one('${target}').`);
224
+ }
225
+ };
226
+ for (const [key, field] of Object.entries(fields)) {
227
+ if (field.kind === 'monetary')
228
+ expectTarget(key, field.currencyField, 'res.currency', 'currency');
229
+ if (field.kind === 'quantity')
230
+ expectTarget(key, field.uomField, 'uom.uom', 'uom');
231
+ if (typeof field.compute === 'string' && typeof methods[field.compute] !== 'function') {
232
+ fail(name, `field '${key}' has compute: '${field.compute}', which is not a method of this model.`, 'Add the method under `methods`, or pass an inline compute function.');
233
+ }
234
+ }
235
+ // --- order, recName, tracking
236
+ const order = (definition.order ?? ['id asc']).map((spec) => {
237
+ const [field, direction = 'asc', ...rest] = spec.split(' ');
238
+ if (field === undefined || rest.length > 0 || (direction !== 'asc' && direction !== 'desc')) {
239
+ fail(name, `order entry '${spec}' is malformed.`, "Use 'field', 'field asc' or 'field desc'.");
240
+ }
241
+ if (!has(field) || fields[field]?.kind === 'one2many' || fields[field]?.kind === 'many2many') {
242
+ fail(name, `order refers to '${field}', which is not a sortable field.`, 'Order by scalar fields or many2one ids; sort by related names with a path (query layer).');
243
+ }
244
+ return { field, direction };
245
+ });
246
+ const recName = definition.recName ?? (has('name') ? 'name' : 'id');
247
+ if (!has(recName) ||
248
+ fields[recName]?.kind === 'one2many' ||
249
+ fields[recName]?.kind === 'many2many') {
250
+ fail(name, `recName '${recName}' is not a scalar field.`, 'Choose a char/text field (or leave it to `name`).');
251
+ }
252
+ const backdate = definition.backdate;
253
+ if (backdate !== undefined) {
254
+ const kind = fields[backdate.field]?.kind;
255
+ if (kind !== 'date' && kind !== 'datetime')
256
+ fail(name, `backdate.field '${backdate.field}' is not a date or datetime field.`, 'Point it at the document date, e.g. backdate: { field: "date", permission: "account.backdate" }.');
257
+ if (backdate.graceDays !== undefined &&
258
+ (!Number.isInteger(backdate.graceDays) || backdate.graceDays < 0))
259
+ fail(name, 'backdate.graceDays must be a non-negative integer.', 'Use 0 for "today only".');
260
+ }
261
+ const delegates = [...(definition.delegates ?? [])];
262
+ for (const key of delegates) {
263
+ const field = fields[key];
264
+ if (field?.kind !== 'many2one' || field.required !== true || field.ondelete !== 'cascade')
265
+ fail(name, `delegates '${key}' must be a required many2one with ondelete: 'cascade'.`, `Declare ${key}: f.many2one('<parent model>', { required: true, ondelete: 'cascade' }).`);
266
+ }
267
+ const hierarchy = definition.hierarchy;
268
+ if (hierarchy !== undefined) {
269
+ const parent = fields[hierarchy.parent];
270
+ if (parent?.kind !== 'many2one' || parent.target !== name)
271
+ fail(name, `hierarchy.parent '${hierarchy.parent}' is not a many2one to ${name}.`, `Declare ${hierarchy.parent}: f.many2one('${name}', { ondelete: 'cascade' }).`);
272
+ const path = fields[hierarchy.path];
273
+ if (path?.kind !== 'char' || !path.readonly || path.computed)
274
+ fail(name, `hierarchy.path '${hierarchy.path}' must be a readonly char field.`, `Declare ${hierarchy.path}: f.char({ readonly: true, index: true }); the engine fills it.`);
275
+ }
276
+ const tracking = [...(definition.tracking ?? [])];
277
+ for (const key of tracking)
278
+ if (!has(key))
279
+ fail(name, `tracking refers to unknown field '${key}'.`, 'List existing field keys.');
280
+ // --- transitions become methods (RFC 0010 §7.1)
281
+ for (const [key, field] of Object.entries(fields)) {
282
+ if (field.kind !== 'state')
283
+ continue;
284
+ const transitions = field.transitions;
285
+ for (const tname of Object.keys(transitions)) {
286
+ const existing = methods[tname];
287
+ if (existing !== undefined && transitionOf(existing) === undefined)
288
+ fail(name, `transition '${tname}' of state field '${key}' clashes with method '${tname}'.`, 'A transition is already a method: remove the declared one, or wrap it with overrides in an extension.');
289
+ if (RESERVED_KEYS.includes(tname))
290
+ fail(name, `transition '${tname}' is a reserved name.`, 'Rename the transition; it would shadow the recordset API.');
291
+ if (existing === undefined)
292
+ methods[tname] = markTransition(function transition() {
293
+ return this.transition(key, tname);
294
+ }, key, tname);
295
+ }
296
+ }
297
+ // --- SQL constraints
298
+ const sqlConstraints = Object.entries(definition.sqlConstraints ?? {}).map(([key, spec]) => {
299
+ if (!FIELD_KEY.test(key))
300
+ fail(name, `sqlConstraints key '${key}' is not camelCase.`, "Use keys like 'nameUniquePerCompany'.");
301
+ if (typeof spec.message !== 'string' || spec.message.trim() === '') {
302
+ fail(name, `sqlConstraints '${key}' has no message.`, 'Give users a message that says what went wrong and what to do.');
303
+ }
304
+ const sqlConstraintName = sqlName(table, snakeCase(key), name);
305
+ if ('unique' in spec) {
306
+ if (spec.unique.length === 0)
307
+ fail(name, `unique constraint '${key}' lists no fields.`, 'List at least one stored field.');
308
+ const cols = spec.unique.map((field) => {
309
+ const column = columns[field];
310
+ if (!has(field) || column === undefined)
311
+ fail(name, `unique constraint '${key}' refers to '${field}', which is not a stored field.`, 'Use stored scalar or many2one fields.');
312
+ return column;
313
+ });
314
+ if (spec.where !== undefined && !isSql(spec.where))
315
+ fail(name, `unique constraint '${key}' has a non-sql where.`, 'Write it with the sql`...` tag.');
316
+ return {
317
+ key,
318
+ name: sqlConstraintName,
319
+ kind: 'unique',
320
+ fields: [...spec.unique],
321
+ columns: cols,
322
+ where: spec.where,
323
+ message: spec.message,
324
+ };
325
+ }
326
+ if (!isSql(spec.check))
327
+ fail(name, `check constraint '${key}' is not a sql fragment.`, 'Write it with the sql`...` tag, e.g. sql`debit = 0 OR credit = 0`.');
328
+ return {
329
+ key,
330
+ name: sqlConstraintName,
331
+ kind: 'check',
332
+ fields: [],
333
+ columns: [],
334
+ check: spec.check,
335
+ message: spec.message,
336
+ };
337
+ });
338
+ // --- indexes
339
+ const indexes = (definition.indexes ?? []).map((spec) => {
340
+ if (spec.fields.length === 0)
341
+ fail(name, 'an index lists no fields.', 'List at least one stored field.');
342
+ const cols = spec.fields.map((field) => {
343
+ const column = columns[field];
344
+ if (!has(field) || column === undefined)
345
+ fail(name, `an index refers to '${field}', which is not a stored field.`, 'Use stored scalar or many2one fields.');
346
+ return column;
347
+ });
348
+ if (spec.where !== undefined && !isSql(spec.where))
349
+ fail(name, 'an index has a non-sql where.', 'Write it with the sql`...` tag.');
350
+ return {
351
+ name: sqlName(table, `${cols.join('_')}_idx`, name),
352
+ fields: [...spec.fields],
353
+ columns: cols,
354
+ unique: spec.unique ?? false,
355
+ where: spec.where,
356
+ method: spec.method ?? 'btree',
357
+ };
358
+ });
359
+ // --- business constraints
360
+ const constraints = Object.entries(definition.constraints ?? {}).map(([key, spec]) => {
361
+ if (!FIELD_KEY.test(key))
362
+ fail(name, `constraints key '${key}' is not camelCase.`, "Use keys like 'validityAfterOrderDate'.");
363
+ if (!Array.isArray(spec.depends) || spec.depends.length === 0)
364
+ fail(name, `constraint '${key}' has no depends.`, 'List the fields whose change triggers the check.');
365
+ if (typeof spec.check !== 'function')
366
+ fail(name, `constraint '${key}' has no check function.`, 'check(records) returns the failing records.');
367
+ if (typeof spec.message !== 'string' && typeof spec.message !== 'function')
368
+ fail(name, `constraint '${key}' has no message.`, 'Give a message string or a function of the failing records.');
369
+ return { key, ...spec };
370
+ });
371
+ // --- multi-company consistency (RFC 0003 §7.4): a synthesized constraint over the checkCompany many2ones
372
+ const checked = Object.entries(fields)
373
+ .filter(([, f]) => f.kind === 'many2one' && f.checkCompany === true)
374
+ .map(([k]) => k);
375
+ if (checked.length > 0) {
376
+ if (definition.companyScoped === undefined)
377
+ fail(name, `checkCompany on '${checked[0]}' needs a companyScoped model.`, 'Set companyScoped: { required: true } (or false) on the model, or drop checkCompany.');
378
+ if (constraints.some((c) => c.key === 'companyConsistency'))
379
+ fail(name, "'companyConsistency' is a reserved constraint key.", 'It is synthesized for checkCompany fields; rename yours.');
380
+ constraints.push({
381
+ key: 'companyConsistency',
382
+ depends: ['company', ...checked],
383
+ check: companyConsistencyCheck(name, checked),
384
+ message: 'Records must reference shared records or records of their own company.',
385
+ });
386
+ }
387
+ // --- partitioning (RFC 0015 §7.2)
388
+ const partition = definition.partition;
389
+ if (partition !== undefined) {
390
+ if (!['range', 'list', 'hash'].includes(partition.by))
391
+ fail(name, `partition.by ${JSON.stringify(partition.by)} is unknown.`, "Use 'range', 'list' or 'hash'.");
392
+ const keyField = fields[partition.key];
393
+ if (keyField === undefined || columns[partition.key] === undefined || keyField.computed)
394
+ fail(name, `partition key '${partition.key}' is not a stored field.`, 'Partition on a stored field such as a date or the company.');
395
+ else if (!keyField.required)
396
+ fail(name, `partition key '${partition.key}' must be required.`, 'It is part of the primary key: give it required: true (and a default if needed).');
397
+ for (const c of sqlConstraints) {
398
+ if (c.kind === 'unique' && !c.fields.includes(partition.key))
399
+ fail(name, `unique constraint '${c.key}' does not include the partition key '${partition.key}'.`, 'PostgreSQL enforces uniqueness per partition only when the key is part of it: add the key to the constraint.');
400
+ }
401
+ }
402
+ // --- access and record rules (RFC 0014)
403
+ const access = Object.freeze({ ...(definition.access ?? {}) });
404
+ assertAccessSpec(access, `Model '${name}'`);
405
+ const rules = {};
406
+ for (const [key, rule] of Object.entries(definition.rules ?? {})) {
407
+ if (!FIELD_KEY.test(key))
408
+ fail(name, `rules key '${key}' is not camelCase.`, "Use keys like 'ownOrders'.");
409
+ assertRuleSpec(rule, `Model '${name}' rule '${key}'`);
410
+ rules[key] = Object.freeze({ ...rule });
411
+ }
412
+ // --- onchange handlers
413
+ const onchange = {};
414
+ for (const [key, fn] of Object.entries(definition.onchange ?? {})) {
415
+ if (!has(key))
416
+ fail(name, `onchange key '${key}' is not a field.`, `Fields: ${keys.join(', ')}.`);
417
+ if (typeof fn !== 'function')
418
+ fail(name, `onchange '${key}' is not a function.`, 'Pass (draft, env) => { ... }.');
419
+ onchange[key] = fn;
420
+ }
421
+ const model = {
422
+ name,
423
+ table,
424
+ label: definition.label ?? humanize(name),
425
+ fields: Object.freeze(fields),
426
+ columns: Object.freeze(columns),
427
+ order: Object.freeze(order),
428
+ recName,
429
+ archivable: definition.archivable === true,
430
+ companyScoped: definition.companyScoped === undefined
431
+ ? undefined
432
+ : Object.freeze({ ...definition.companyScoped }),
433
+ tracking: Object.freeze(tracking),
434
+ backdate: backdate === undefined ? undefined : Object.freeze({ ...backdate }),
435
+ hierarchy: hierarchy === undefined ? undefined : Object.freeze({ ...hierarchy }),
436
+ delegates: Object.freeze(delegates),
437
+ history: definition.history === true,
438
+ indexes: Object.freeze(indexes),
439
+ sqlConstraints: Object.freeze(sqlConstraints),
440
+ constraints: Object.freeze(constraints),
441
+ onchange: Object.freeze(onchange),
442
+ access,
443
+ rules: Object.freeze(rules),
444
+ partition: partition === undefined ? undefined : Object.freeze({ ...partition }),
445
+ methods: Object.freeze(methods),
446
+ declaredFields: Object.freeze(Object.keys(user)),
447
+ definition: Object.freeze({ ...definition }),
448
+ describe() {
449
+ return describeModel(model);
450
+ },
451
+ };
452
+ Object.freeze(model);
453
+ models.add(model);
454
+ void keys;
455
+ return model;
456
+ }
457
+ // ----------------------------------------------------------------------------------------------------- describe
458
+ function describeField(field, column, trackedByModel) {
459
+ const base = {
460
+ kind: field.kind,
461
+ label: field.label ?? '',
462
+ help: field.help ?? null,
463
+ column: column ?? null,
464
+ pgType: field.pgType,
465
+ required: field.required,
466
+ readonly: field.readonly,
467
+ store: field.store,
468
+ computed: field.computed,
469
+ compute: field.compute === undefined
470
+ ? null
471
+ : typeof field.compute === 'string'
472
+ ? field.compute
473
+ : 'inline',
474
+ depends: [...field.depends],
475
+ hasDefault: field.default !== undefined,
476
+ index: field.index === undefined ? null : field.index === true ? 'btree' : field.index,
477
+ copy: field.copy,
478
+ // Tracked either on the field or in the model's `tracking` list.
479
+ tracking: field.tracking || trackedByModel,
480
+ translate: field.translate,
481
+ sequence: field.sequence === undefined ? null : { ...field.sequence },
482
+ deprecated: field.deprecated ?? null,
483
+ groups: field.groups,
484
+ };
485
+ const extra = {};
486
+ const x = field;
487
+ for (const key of [
488
+ 'size',
489
+ 'scale',
490
+ 'precision',
491
+ 'currencyField',
492
+ 'uomField',
493
+ 'target',
494
+ 'inverseField',
495
+ 'relation',
496
+ 'ondelete',
497
+ 'checkCompany',
498
+ 'initial',
499
+ 'identity',
500
+ 'extensible',
501
+ 'sanitize',
502
+ 'encrypted',
503
+ ]) {
504
+ if (x[key] !== undefined)
505
+ extra[key] = x[key];
506
+ }
507
+ if (field.kind === 'selection' || field.kind === 'state') {
508
+ const selection = x['selection'];
509
+ extra['selection'] =
510
+ typeof selection === 'function'
511
+ ? 'dynamic'
512
+ : selection.map(([k, v]) => [k, v]);
513
+ }
514
+ if (field.kind === 'state') {
515
+ const transitions = x['transitions'];
516
+ extra['transitions'] = Object.fromEntries(Object.entries(transitions).map(([k, t]) => [
517
+ k,
518
+ {
519
+ from: [...t.from],
520
+ to: t.to,
521
+ guarded: typeof t.guard === 'function',
522
+ },
523
+ ]));
524
+ }
525
+ return { ...base, ...extra };
526
+ }
527
+ function describeModel(model) {
528
+ return {
529
+ name: model.name,
530
+ label: model.label,
531
+ table: model.table,
532
+ recName: model.recName,
533
+ order: model.order.map((o) => ({ ...o })),
534
+ archivable: model.archivable,
535
+ companyScoped: model.companyScoped ?? null,
536
+ tracking: [...model.tracking],
537
+ fields: Object.fromEntries(Object.entries(model.fields).map(([key, field]) => [
538
+ key,
539
+ describeField(field, model.columns[key], model.tracking.includes(key)),
540
+ ])),
541
+ sqlConstraints: model.sqlConstraints.map((c) => ({
542
+ key: c.key,
543
+ name: c.name,
544
+ kind: c.kind,
545
+ fields: [...c.fields],
546
+ message: c.message,
547
+ })),
548
+ indexes: model.indexes.map((i) => ({
549
+ name: i.name,
550
+ fields: [...i.fields],
551
+ unique: i.unique,
552
+ method: i.method,
553
+ partial: i.where !== undefined,
554
+ })),
555
+ constraints: model.constraints.map((c) => ({
556
+ key: c.key,
557
+ depends: [...c.depends],
558
+ message: typeof c.message === 'string' ? c.message : null,
559
+ })),
560
+ methods: Object.keys(model.methods),
561
+ onchange: Object.keys(model.onchange),
562
+ access: model.access,
563
+ rules: model.rules,
564
+ partition: model.partition ?? null,
565
+ };
566
+ }
@@ -0,0 +1,31 @@
1
+ import type { AnyModel } from './model.js';
2
+ /** How a model's table is partitioned. */
3
+ export interface PartitionSpec {
4
+ readonly by: 'range' | 'list' | 'hash';
5
+ /** The field key the table is partitioned on; it becomes part of the primary key. */
6
+ readonly key: string;
7
+ }
8
+ /** One partition to create. */
9
+ export type PartitionBound = {
10
+ readonly name: string;
11
+ readonly from: string | number;
12
+ readonly to: string | number;
13
+ } | {
14
+ readonly name: string;
15
+ readonly values: readonly (string | number)[];
16
+ } | {
17
+ readonly name: string;
18
+ readonly modulus: number;
19
+ readonly remainder: number;
20
+ } | {
21
+ readonly name: string;
22
+ readonly default: true;
23
+ };
24
+ /** `CREATE TABLE IF NOT EXISTS <name> PARTITION OF <table> FOR VALUES ...` for each bound. */
25
+ export declare function partitionStatements(model: AnyModel, bounds: readonly PartitionBound[]): string[];
26
+ /** Monthly (or yearly) range partitions covering `[from, to)`, named `<table>_YYYY_MM` / `<table>_YYYY`. */
27
+ export declare function rangePartitions(model: AnyModel, options: {
28
+ readonly from: string;
29
+ readonly to: string;
30
+ readonly interval?: 'month' | 'year';
31
+ }): PartitionBound[];
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Partitioned models (RFC 0015 §7.2): a model whose table is `PARTITION BY RANGE | LIST | HASH (key)`, for the
3
+ * high-volume append tables of an ERP (journal items, stock moves, audit-like logs). The partitions themselves are
4
+ * plain DDL created ahead of time with {@link partitionStatements} / {@link rangePartitions}.
5
+ */
6
+ import { InvalidModelError } from '../errors.js';
7
+ const IDENTIFIER = /^[a-z_][a-z0-9_]*$/;
8
+ function ident(name) {
9
+ if (!IDENTIFIER.test(name) || name.length > 63) {
10
+ throw new InvalidModelError(name, 'is not a valid partition name.', 'Use lower-case snake_case, at most 63 characters.');
11
+ }
12
+ return `"${name}"`;
13
+ }
14
+ function literal(value) {
15
+ if (typeof value === 'number') {
16
+ if (!Number.isFinite(value))
17
+ throw new InvalidModelError('partition', `bound ${value} is not finite.`, 'Use finite numbers or strings.');
18
+ return String(value);
19
+ }
20
+ return `'${value.replaceAll("'", "''")}'`;
21
+ }
22
+ /** `CREATE TABLE IF NOT EXISTS <name> PARTITION OF <table> FOR VALUES ...` for each bound. */
23
+ export function partitionStatements(model, bounds) {
24
+ const spec = model.partition;
25
+ if (spec === undefined) {
26
+ throw new InvalidModelError(model.name, 'is not partitioned.', "Declare partition: { by: 'range', key: 'date' } on the model.");
27
+ }
28
+ return bounds.map((b) => {
29
+ let clause;
30
+ if ('default' in b)
31
+ clause = 'DEFAULT';
32
+ else if ('from' in b) {
33
+ if (spec.by !== 'range')
34
+ throw new InvalidModelError(model.name, `partition '${b.name}' has range bounds, but the table is partitioned by ${spec.by}.`, 'Use bounds matching the strategy.');
35
+ clause = `FOR VALUES FROM (${literal(b.from)}) TO (${literal(b.to)})`;
36
+ }
37
+ else if ('values' in b) {
38
+ if (spec.by !== 'list')
39
+ throw new InvalidModelError(model.name, `partition '${b.name}' has list values, but the table is partitioned by ${spec.by}.`, 'Use bounds matching the strategy.');
40
+ clause = `FOR VALUES IN (${b.values.map(literal).join(', ')})`;
41
+ }
42
+ else {
43
+ if (spec.by !== 'hash')
44
+ throw new InvalidModelError(model.name, `partition '${b.name}' has hash bounds, but the table is partitioned by ${spec.by}.`, 'Use bounds matching the strategy.');
45
+ clause = `FOR VALUES WITH (MODULUS ${Math.trunc(b.modulus)}, REMAINDER ${Math.trunc(b.remainder)})`;
46
+ }
47
+ return `CREATE TABLE IF NOT EXISTS ${ident(b.name)} PARTITION OF ${ident(model.table)} ${clause}`;
48
+ });
49
+ }
50
+ /** Monthly (or yearly) range partitions covering `[from, to)`, named `<table>_YYYY_MM` / `<table>_YYYY`. */
51
+ export function rangePartitions(model, options) {
52
+ const interval = options.interval ?? 'month';
53
+ const [fy = 0, fm = 1] = options.from.split('-').map(Number);
54
+ const [ty = 0, tm = 1] = options.to.split('-').map(Number);
55
+ const out = [];
56
+ let y = fy;
57
+ let m = interval === 'year' ? 1 : fm;
58
+ const pad = (n) => String(n).padStart(2, '0');
59
+ while (y < ty || (y === ty && (interval === 'year' ? false : m < tm))) {
60
+ const ny = interval === 'year' ? y + 1 : m === 12 ? y + 1 : y;
61
+ const nm = interval === 'year' ? 1 : m === 12 ? 1 : m + 1;
62
+ out.push({
63
+ name: interval === 'year' ? `${model.table}_${y}` : `${model.table}_${y}_${pad(m)}`,
64
+ from: `${y}-${pad(m)}-01`,
65
+ to: `${ny}-${pad(nm)}-01`,
66
+ });
67
+ y = ny;
68
+ m = nm;
69
+ }
70
+ return out;
71
+ }