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.
Files changed (145) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +89 -2
  3. package/dist/audit/index.d.ts +57 -0
  4. package/dist/audit/index.js +94 -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 +149 -0
  9. package/dist/cli/config.d.ts +18 -0
  10. package/dist/cli/config.js +47 -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 +82 -0
  15. package/dist/cli/generate/render.d.ts +23 -0
  16. package/dist/cli/generate/render.js +200 -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/core/compute/graph.d.ts +52 -0
  28. package/dist/core/compute/graph.js +162 -0
  29. package/dist/core/env/env.d.ts +295 -0
  30. package/dist/core/env/env.js +631 -0
  31. package/dist/core/env/identity.d.ts +33 -0
  32. package/dist/core/env/identity.js +49 -0
  33. package/dist/core/env/inspector.d.ts +55 -0
  34. package/dist/core/env/inspector.js +85 -0
  35. package/dist/core/env/time.d.ts +12 -0
  36. package/dist/core/env/time.js +38 -0
  37. package/dist/core/errors.d.ts +242 -0
  38. package/dist/core/errors.js +339 -0
  39. package/dist/core/index.d.ts +43 -0
  40. package/dist/core/index.js +34 -0
  41. package/dist/core/model/company.d.ts +6 -0
  42. package/dist/core/model/company.js +31 -0
  43. package/dist/core/model/faces.d.ts +42 -0
  44. package/dist/core/model/faces.js +1 -0
  45. package/dist/core/model/field.d.ts +446 -0
  46. package/dist/core/model/field.js +398 -0
  47. package/dist/core/model/generated.d.ts +75 -0
  48. package/dist/core/model/generated.js +1 -0
  49. package/dist/core/model/id.d.ts +33 -0
  50. package/dist/core/model/id.js +4 -0
  51. package/dist/core/model/model.d.ts +347 -0
  52. package/dist/core/model/model.js +538 -0
  53. package/dist/core/model/partition.d.ts +31 -0
  54. package/dist/core/model/partition.js +71 -0
  55. package/dist/core/money/currency.d.ts +39 -0
  56. package/dist/core/money/currency.js +37 -0
  57. package/dist/core/money/decimal.d.ts +26 -0
  58. package/dist/core/money/decimal.js +51 -0
  59. package/dist/core/money/fx.d.ts +60 -0
  60. package/dist/core/money/fx.js +109 -0
  61. package/dist/core/money/money.d.ts +84 -0
  62. package/dist/core/money/money.js +173 -0
  63. package/dist/core/money/quantity.d.ts +67 -0
  64. package/dist/core/money/quantity.js +108 -0
  65. package/dist/core/money/rounding.d.ts +11 -0
  66. package/dist/core/money/rounding.js +12 -0
  67. package/dist/core/recordset/audit.d.ts +25 -0
  68. package/dist/core/recordset/audit.js +205 -0
  69. package/dist/core/recordset/compute.d.ts +34 -0
  70. package/dist/core/recordset/compute.js +405 -0
  71. package/dist/core/recordset/constraints.d.ts +9 -0
  72. package/dist/core/recordset/constraints.js +61 -0
  73. package/dist/core/recordset/domain.d.ts +27 -0
  74. package/dist/core/recordset/domain.js +228 -0
  75. package/dist/core/recordset/onchange.d.ts +43 -0
  76. package/dist/core/recordset/onchange.js +207 -0
  77. package/dist/core/recordset/recordset.d.ts +101 -0
  78. package/dist/core/recordset/recordset.js +723 -0
  79. package/dist/core/recordset/relations.d.ts +15 -0
  80. package/dist/core/recordset/relations.js +13 -0
  81. package/dist/core/recordset/rls.d.ts +15 -0
  82. package/dist/core/recordset/rls.js +108 -0
  83. package/dist/core/recordset/security.d.ts +42 -0
  84. package/dist/core/recordset/security.js +184 -0
  85. package/dist/core/recordset/sequences.d.ts +31 -0
  86. package/dist/core/recordset/sequences.js +154 -0
  87. package/dist/core/recordset/sqlErrors.d.ts +6 -0
  88. package/dist/core/recordset/sqlErrors.js +39 -0
  89. package/dist/core/recordset/transitions.d.ts +10 -0
  90. package/dist/core/recordset/transitions.js +77 -0
  91. package/dist/core/recordset/types.d.ts +296 -0
  92. package/dist/core/recordset/types.js +8 -0
  93. package/dist/core/recordset/values.d.ts +27 -0
  94. package/dist/core/recordset/values.js +147 -0
  95. package/dist/core/recordset/writes.d.ts +37 -0
  96. package/dist/core/recordset/writes.js +581 -0
  97. package/dist/core/registry/ddl.d.ts +22 -0
  98. package/dist/core/registry/ddl.js +127 -0
  99. package/dist/core/registry/extension.d.ts +94 -0
  100. package/dist/core/registry/extension.js +90 -0
  101. package/dist/core/registry/module.d.ts +80 -0
  102. package/dist/core/registry/module.js +96 -0
  103. package/dist/core/registry/registry.d.ts +105 -0
  104. package/dist/core/registry/registry.js +496 -0
  105. package/dist/driver-pg/driver.d.ts +86 -0
  106. package/dist/driver-pg/driver.js +176 -0
  107. package/dist/driver-pg/errors.d.ts +72 -0
  108. package/dist/driver-pg/errors.js +182 -0
  109. package/dist/driver-pg/index.d.ts +7 -0
  110. package/dist/driver-pg/index.js +7 -0
  111. package/dist/i18n/index.d.ts +25 -0
  112. package/dist/i18n/index.js +51 -0
  113. package/dist/migrate/apply.d.ts +78 -0
  114. package/dist/migrate/apply.js +167 -0
  115. package/dist/migrate/catalog.d.ts +10 -0
  116. package/dist/migrate/catalog.js +122 -0
  117. package/dist/migrate/diff.d.ts +98 -0
  118. package/dist/migrate/diff.js +160 -0
  119. package/dist/migrate/errors.d.ts +21 -0
  120. package/dist/migrate/errors.js +31 -0
  121. package/dist/migrate/index.d.ts +18 -0
  122. package/dist/migrate/index.js +18 -0
  123. package/dist/migrate/render.d.ts +5 -0
  124. package/dist/migrate/render.js +101 -0
  125. package/dist/migrate/schema.d.ts +61 -0
  126. package/dist/migrate/schema.js +195 -0
  127. package/dist/security/index.d.ts +123 -0
  128. package/dist/security/index.js +262 -0
  129. package/dist/sequence/index.d.ts +63 -0
  130. package/dist/sequence/index.js +106 -0
  131. package/dist/sql/ast.d.ts +49 -0
  132. package/dist/sql/ast.js +47 -0
  133. package/dist/sql/builder/builder.d.ts +215 -0
  134. package/dist/sql/builder/builder.js +308 -0
  135. package/dist/sql/builder/expression.d.ts +80 -0
  136. package/dist/sql/builder/expression.js +126 -0
  137. package/dist/sql/compile.d.ts +18 -0
  138. package/dist/sql/compile.js +41 -0
  139. package/dist/sql/errors.d.ts +13 -0
  140. package/dist/sql/errors.js +16 -0
  141. package/dist/sql/index.d.ts +19 -0
  142. package/dist/sql/index.js +19 -0
  143. package/dist/sql/tag.d.ts +42 -0
  144. package/dist/sql/tag.js +95 -0
  145. package/package.json +82 -4
@@ -0,0 +1,339 @@
1
+ /**
2
+ * Base class of every error raised by `@shutro/core`. The message says what went wrong and ends with
3
+ * {@link ShutroError.hint}, which says how to fix it (`CLAUDE.md` coding rules).
4
+ */
5
+ export class ShutroError extends Error {
6
+ /** Machine-readable reason. */
7
+ code;
8
+ /** How to fix the problem. Also included at the end of `message`. */
9
+ hint;
10
+ constructor(code, problem, hint, options) {
11
+ super(`${problem} ${hint}`, options?.cause === undefined ? undefined : { cause: options.cause });
12
+ this.name = new.target.name;
13
+ this.code = code;
14
+ this.hint = hint;
15
+ }
16
+ }
17
+ /** A JavaScript `number` that isn't a safe integer was used where an exact decimal is required. */
18
+ export class NonIntegerNumberError extends ShutroError {
19
+ constructor(problem, hint) {
20
+ super('NON_INTEGER_NUMBER', problem, hint);
21
+ }
22
+ }
23
+ /** A string or Decimal that isn't a finite decimal number. */
24
+ export class InvalidDecimalError extends ShutroError {
25
+ constructor(problem, hint) {
26
+ super('INVALID_DECIMAL', problem, hint);
27
+ }
28
+ }
29
+ /** Division of a money amount or quantity by zero. */
30
+ export class DivisionByZeroError extends ShutroError {
31
+ constructor(problem, hint) {
32
+ super('DIVISION_BY_ZERO', problem, hint);
33
+ }
34
+ }
35
+ /** Invalid currency definition. */
36
+ export class InvalidCurrencyError extends ShutroError {
37
+ constructor(problem, hint) {
38
+ super('INVALID_CURRENCY', problem, hint);
39
+ }
40
+ }
41
+ /** Arithmetic or comparison between amounts in different currencies (RFC 0006 R4). */
42
+ export class CurrencyMismatchError extends ShutroError {
43
+ constructor(problem, hint) {
44
+ super('CURRENCY_MISMATCH', problem, hint);
45
+ }
46
+ }
47
+ /** Invalid ratios passed to `Money.allocate()`. */
48
+ export class InvalidAllocationError extends ShutroError {
49
+ constructor(problem, hint) {
50
+ super('INVALID_ALLOCATION', problem, hint);
51
+ }
52
+ }
53
+ /** `Money.sum([])` without a currency. */
54
+ export class EmptyMoneySumError extends ShutroError {
55
+ constructor(problem, hint) {
56
+ super('MONEY_EMPTY_SUM', problem, hint);
57
+ }
58
+ }
59
+ /** Invalid unit-of-measure definition. */
60
+ export class InvalidUomError extends ShutroError {
61
+ constructor(problem, hint) {
62
+ super('INVALID_UOM', problem, hint);
63
+ }
64
+ }
65
+ /** Arithmetic or comparison between quantities in different units. */
66
+ export class UomMismatchError extends ShutroError {
67
+ constructor(problem, hint) {
68
+ super('UOM_MISMATCH', problem, hint);
69
+ }
70
+ }
71
+ /** Conversion between units of different categories (e.g. units to kilograms). */
72
+ export class IncompatibleUomCategoryError extends ShutroError {
73
+ constructor(problem, hint) {
74
+ super('UOM_CATEGORY_MISMATCH', problem, hint);
75
+ }
76
+ }
77
+ /** No environment is active (code ran outside `shutro.run()`), RFC 0003 §7.7. */
78
+ export class NoEnvironmentError extends ShutroError {
79
+ constructor() {
80
+ super('NO_ENVIRONMENT', 'No Shutro environment is active.', 'Wrap the call in shutro.run({ user, company }, (env) => ...) or use the env of an existing recordset.');
81
+ }
82
+ }
83
+ /** An environment was used outside its transaction scope (RFC 0003 §7.7). */
84
+ export class TransactionScopeError extends ShutroError {
85
+ constructor(problem, hint) {
86
+ super('TRANSACTION_SCOPE', problem, hint);
87
+ }
88
+ }
89
+ /** Every retry of a transaction hit a serialization failure or deadlock (RFC 0003 §7.5). */
90
+ export class ConcurrentUpdateError extends ShutroError {
91
+ constructor(attempts, cause) {
92
+ super('CONCURRENT_UPDATE', `The transaction conflicted with concurrent transactions on all ${attempts} attempts.`, 'Reduce contention: lock records in a consistent order, keep transactions short, or process the data in smaller chunks (shutro.forEachChunk).', { cause });
93
+ }
94
+ }
95
+ /** Invalid user, company, language, time zone or reason passed to `shutro.run()` or a derived environment. */
96
+ export class InvalidIdentityError extends ShutroError {
97
+ constructor(problem, hint) {
98
+ super('INVALID_IDENTITY', problem, hint);
99
+ }
100
+ }
101
+ /** `withCompany()` outside the user's allowed companies (RFC 0003 §7.2). */
102
+ export class CompanyNotAllowedError extends ShutroError {
103
+ constructor(company, allowed) {
104
+ super('COMPANY_NOT_ALLOWED', `Company ${company} is not among the allowed companies [${allowed.join(', ')}] of this environment.`, 'Select the company in the session (allowed companies), or run the operation under env.asSuperuser({ reason }, ...) if it is a system task.');
105
+ }
106
+ }
107
+ /** A field definition that can't be right (RFC 0001): bad size, scale, selection, transition, relation option, ... */
108
+ export class InvalidFieldError extends ShutroError {
109
+ constructor(problem, hint) {
110
+ super('INVALID_FIELD', problem, hint);
111
+ }
112
+ }
113
+ /** A model definition that can't be right (RFC 0001): reserved keys, column collisions, bad sibling references, ... */
114
+ export class InvalidModelError extends ShutroError {
115
+ constructor(model, problem, hint) {
116
+ super('INVALID_MODEL', `Model '${model}': ${problem}`, hint);
117
+ }
118
+ }
119
+ /** A module definition that can't be right (RFC 0002 §7.1). */
120
+ export class InvalidModuleError extends ShutroError {
121
+ constructor(problem, hint) {
122
+ super('INVALID_MODULE', problem, hint);
123
+ }
124
+ }
125
+ /** Two different module objects share a name (e.g. two copies of `base` from different package versions). */
126
+ export class DuplicateModuleError extends ShutroError {
127
+ constructor(name) {
128
+ super('DUPLICATE_MODULE', `Two different modules are named '${name}'.`, 'Modules are identified by name; dedupe the package (one version of each module) or rename one of them.');
129
+ }
130
+ }
131
+ /** The same model name is defined twice (in one module or in two). */
132
+ export class DuplicateModelError extends ShutroError {
133
+ constructor(model, modules) {
134
+ super('DUPLICATE_MODEL', `Model '${model}' is defined more than once (in ${modules.map((m) => `'${m}'`).join(' and ')}).`, 'A model has exactly one owner; extend it from the other module with extendModel() instead of defining it again.');
135
+ }
136
+ }
137
+ /** A module references a model owned by a module it doesn't depend on (RFC 0002 W2). */
138
+ export class UndeclaredDependencyError extends ShutroError {
139
+ constructor(module, model, owner, via) {
140
+ super('UNDECLARED_DEPENDENCY', `Module '${module}' references '${model}' (owned by '${owner}') in ${via}, but does not depend on '${owner}'.`, `Add the '${owner}' module to the depends of '${module}'. Only models of a module and its transitive dependencies may be referenced.`);
141
+ }
142
+ }
143
+ /** A model name that no loaded module defines. */
144
+ export class UnknownModelError extends ShutroError {
145
+ constructor(model, via) {
146
+ super('UNKNOWN_MODEL', via === undefined
147
+ ? `No loaded module defines model '${model}'.`
148
+ : `${via} refers to model '${model}', which no loaded module defines.`, 'Check the model name, and make sure the module that defines it is loaded (directly or as a dependency).');
149
+ }
150
+ }
151
+ /** A one2many whose inverse field doesn't point back, or another broken relation. */
152
+ export class InvalidRelationError extends ShutroError {
153
+ constructor(problem, hint) {
154
+ super('INVALID_RELATION', problem, hint);
155
+ }
156
+ }
157
+ /** A `depends` path that doesn't resolve through real fields. */
158
+ export class InvalidDependsPathError extends ShutroError {
159
+ constructor(problem, hint) {
160
+ super('INVALID_DEPENDS_PATH', problem, hint);
161
+ }
162
+ }
163
+ /** A field was read before it was loaded (RFC 0004 §7.1). */
164
+ export class FieldNotLoadedError extends ShutroError {
165
+ constructor(model, field, hint) {
166
+ super('FIELD_NOT_LOADED', `${model}.${field} is not loaded.`, hint);
167
+ }
168
+ }
169
+ /** `first()` on an empty recordset, or `ensureOne()` on a recordset that isn't exactly one record. */
170
+ export class SingletonError extends ShutroError {
171
+ constructor(model, count, what) {
172
+ super('SINGLETON', `${what}() expected one ${model} record but the recordset has ${count}.`, what === 'first'
173
+ ? 'Check isEmpty() first, or use a search that returns at least one record.'
174
+ : 'Narrow the search, or iterate the recordset when several records are expected.');
175
+ }
176
+ }
177
+ /** A browsed id that doesn't exist (or isn't visible). */
178
+ export class MissingRecordError extends ShutroError {
179
+ constructor(model, ids) {
180
+ super('MISSING_RECORD', `${model} record(s) ${ids.join(', ')} do not exist or are not accessible.`, 'The id may come from stale data or another company; search for the record instead of browsing a remembered id.');
181
+ }
182
+ }
183
+ /** A search domain that can't be compiled (RFC 0005 §7.1). */
184
+ export class InvalidDomainError extends ShutroError {
185
+ constructor(problem, hint) {
186
+ super('INVALID_DOMAIN', problem, hint);
187
+ }
188
+ }
189
+ /** `env.model()` on a Shutro instance created without a registry. */
190
+ export class NoRegistryError extends ShutroError {
191
+ constructor() {
192
+ super('NO_REGISTRY', 'This Shutro instance has no registry, so there are no models.', 'Pass registry: buildRegistry({ modules }) to createShutro().');
193
+ }
194
+ }
195
+ /** Values rejected by `create()` / `write()`: missing required fields, unknown or readonly fields, wrong types (RFC 0001 §7.7). */
196
+ export class ValidationError extends ShutroError {
197
+ model;
198
+ /** The offending field keys. */
199
+ fields;
200
+ constructor(model, fields, problem, hint) {
201
+ super('VALIDATION', `${model}: ${problem}`, hint);
202
+ this.model = model;
203
+ this.fields = Object.freeze([...fields]);
204
+ }
205
+ }
206
+ /** An extension that breaks a view-safety rule (RFC 0002 §7.5) or is malformed. */
207
+ export class InvalidExtensionError extends ShutroError {
208
+ constructor(problem, hint) {
209
+ super('INVALID_EXTENSION', problem, hint);
210
+ }
211
+ }
212
+ /** Two modules contribute the same field, method or constraint key (RFC 0002 §7.6). Never resolved silently. */
213
+ export class ExtensionConflictError extends ShutroError {
214
+ constructor(problem, hint) {
215
+ super('EXTENSION_CONFLICT', problem, hint);
216
+ }
217
+ }
218
+ /** A flag that only a superuser environment may change (RFC 0003 §7.4). */
219
+ export class FlagNotAllowedError extends ShutroError {
220
+ constructor(flag) {
221
+ super('FLAG_NOT_ALLOWED', `The flag '${flag}' can only be changed in a superuser environment.`, 'Disable it inside env.asSuperuser({ reason }, (su) => su.withFlags({ ... })), and only for system tasks such as migrations.');
222
+ }
223
+ }
224
+ /** Computed fields depend on each other in a cycle (RFC 0008 §7.1). */
225
+ export class ComputeCycleError extends ShutroError {
226
+ constructor(chain) {
227
+ super('COMPUTE_CYCLE', `Computed fields depend on each other in a cycle: ${chain.join(' → ')}.`, 'Break the cycle: one of these fields must be computed from stored data only, or become a method.');
228
+ }
229
+ }
230
+ /** A computed field was assigned outside its compute (RFC 0008 §7.5). */
231
+ export class ComputeAssignmentError extends ShutroError {
232
+ constructor(model, key) {
233
+ super('COMPUTE_ASSIGNMENT', `${model}.${key} is computed and can only be assigned inside its compute function.`, 'Write the fields it depends on instead, or give the field an inverse and use write().');
234
+ }
235
+ }
236
+ /** The recompute loop did not converge (RFC 0008 §7.3). */
237
+ export class RecomputeLimitError extends ShutroError {
238
+ constructor(rounds, pending) {
239
+ super('RECOMPUTE_LIMIT', `Recompute did not settle after ${rounds} rounds; still pending: ${pending.join(', ')}.`, 'A compute is probably writing one of its own dependencies. Computes must only assign their computed fields.');
240
+ }
241
+ }
242
+ /** A business constraint found failing records at a flush point (RFC 0009 §7.1). */
243
+ export class ConstraintError extends ShutroError {
244
+ model;
245
+ constraint;
246
+ /** The constraint's `depends`. */
247
+ fields;
248
+ /** Ids of the failing records. */
249
+ records;
250
+ constructor(model, constraint, fields, records, message) {
251
+ super('CONSTRAINT', `${model}: ${message}`, `Constraint '${constraint}' failed for record(s) ${records.join(', ')}.`);
252
+ this.model = model;
253
+ this.constraint = constraint;
254
+ this.fields = Object.freeze([...fields]);
255
+ this.records = Object.freeze([...records]);
256
+ }
257
+ }
258
+ /** PostgreSQL rejected a statement because of a declared `sqlConstraints` entry or a foreign key (RFC 0009 §7.2). */
259
+ export class ConstraintViolationError extends ShutroError {
260
+ model;
261
+ /** The `sqlConstraints` key, or the many2one field for a foreign key. */
262
+ constraint;
263
+ kind;
264
+ fields;
265
+ constructor(model, constraint, kind, fields, message, hint, options) {
266
+ super('CONSTRAINT_VIOLATION', `${model}: ${message}`, hint, options);
267
+ this.model = model;
268
+ this.constraint = constraint;
269
+ this.kind = kind;
270
+ this.fields = Object.freeze([...fields]);
271
+ }
272
+ }
273
+ /** A transition was requested from a state it does not start from (RFC 0010 §7.2). Nothing changed. */
274
+ export class InvalidTransitionError extends ShutroError {
275
+ model;
276
+ transition;
277
+ /** The offending records with their current state. */
278
+ records;
279
+ /** The states the transition starts from. */
280
+ from;
281
+ constructor(model, transition, records, from) {
282
+ super('INVALID_TRANSITION', `${model}: cannot '${transition}' ${records.map((r) => `#${r.id} (${r.state})`).join(', ') || 'these records'}.`, `'${transition}' starts from ${from.join(' | ') || 'no state'}. Check record.transitions() first, or leave the records out of the batch.`);
283
+ this.model = model;
284
+ this.transition = transition;
285
+ this.records = Object.freeze(records.map((r) => Object.freeze({ ...r })));
286
+ this.from = Object.freeze([...from]);
287
+ }
288
+ }
289
+ /** A transition guard returned records that may not transition (RFC 0010 §7.2). Nothing changed. */
290
+ export class TransitionGuardError extends ShutroError {
291
+ model;
292
+ transition;
293
+ records;
294
+ constructor(model, transition, records, message) {
295
+ super('TRANSITION_GUARD', `${model}: ${message}`, `Guard of '${transition}' failed for record(s) ${records.join(', ')}.`);
296
+ this.model = model;
297
+ this.transition = transition;
298
+ this.records = Object.freeze([...records]);
299
+ }
300
+ }
301
+ /** A record references a record of another company through a `checkCompany` many2one (RFC 0003 §7.4). */
302
+ export class CrossCompanyError extends ShutroError {
303
+ model;
304
+ records;
305
+ constructor(model, records) {
306
+ const first = records[0];
307
+ super('CROSS_COMPANY', `${model}: ${records.length} record(s) reference records of another company (e.g. #${first?.id ?? '?'}.${first?.field ?? '?'} belongs to company ${first?.targetCompany ?? '?'}, the record to ${first?.company ?? 'none'}).`, 'Reference a record of the same company or a shared one (no company), or switch the environment company with env.withCompany().');
308
+ this.model = model;
309
+ this.records = Object.freeze(records.map((r) => Object.freeze({ ...r })));
310
+ }
311
+ }
312
+ /** No exchange rate on or before the date (RFC 0006 §7.6), or the rate model is unusable. */
313
+ export class MissingRateError extends ShutroError {
314
+ constructor(problem, hint) {
315
+ super('MISSING_RATE', problem, hint);
316
+ }
317
+ }
318
+ /** A field references a sequence code no module declares (RFC 0012 §7.1). */
319
+ export class UnknownSequenceError extends ShutroError {
320
+ constructor(code, where) {
321
+ super('UNKNOWN_SEQUENCE', `${where} uses the sequence '${code}', which no module declares.`, `Add defineSequence({ code: '${code}', ... }) to the sequences of a module the field's module depends on.`);
322
+ }
323
+ }
324
+ /** An operation the environment may not perform (RFC 0014): model ACL, record rules or field groups. */
325
+ export class AccessError extends ShutroError {
326
+ model;
327
+ perm;
328
+ /** The records out of scope, when the rules denied them. */
329
+ records;
330
+ /** The restricted field, when field groups denied it. */
331
+ field;
332
+ constructor(model, perm, details) {
333
+ super('ACCESS', `${model}: ${details.problem}`, details.hint);
334
+ this.model = model;
335
+ this.perm = perm;
336
+ this.records = Object.freeze([...(details.records ?? [])]);
337
+ this.field = details.field;
338
+ }
339
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@shutro/core`: fields, `defineModel`, recordsets, environment, registry and compute engine (RFCs 0001–0004),
4
+ * and the accounting-safe value types of RFC 0006.
5
+ *
6
+ * Implemented so far: the value types (`Decimal`, `Money`, `Currency`, `Quantity`, `Uom`) and the environment &
7
+ * transaction context (`createShutro`, `Env`).
8
+ */
9
+ export { type AuditAction, type AuditEntry, auditTableStatements, readTrail, type TrailFilter, } from '../audit/index.js';
10
+ export { isTranslations, mergeTranslation, resolveTranslation, type Translations, } from '../i18n/index.js';
11
+ export { type AccessSpec, createKeyRing, defineGroup, EncryptionError, type FieldGroups, type FieldGroupsInput, type GroupDefinition, type KeyRing, type Perm, type RulePerm, type RuleSpec, SecurityDefinitionError, } from '../security/index.js';
12
+ export { defineSequence, InvalidSequenceError, type SequenceDefinition, type SequenceInput, type SequenceReset, } from '../sequence/index.js';
13
+ export { buildComputeGraph, type ComputedField, type ComputeGraph, type PathStep, type Trigger, } from './compute/graph.js';
14
+ export type { VerifiedIdentity } from './env/env.js';
15
+ export { createShutro, Env, type Flags, type Hook, type RunOptions, type ScopeStats, type Shutro, type ShutroOptions, } from './env/env.js';
16
+ export type { Identity, ResolvedIdentity } from './env/identity.js';
17
+ export { createInspector, type InspectedQuery, type Inspector, type InspectorOptions, type InspectorWarning, } from './env/inspector.js';
18
+ export { assertTimeZone, calendarDateIn } from './env/time.js';
19
+ export { AccessError, CompanyNotAllowedError, ComputeAssignmentError, ComputeCycleError, ConcurrentUpdateError, ConstraintError, ConstraintViolationError, CrossCompanyError, CurrencyMismatchError, DivisionByZeroError, DuplicateModelError, DuplicateModuleError, EmptyMoneySumError, ExtensionConflictError, FieldNotLoadedError, FlagNotAllowedError, IncompatibleUomCategoryError, InvalidAllocationError, InvalidCurrencyError, InvalidDecimalError, InvalidDependsPathError, InvalidDomainError, InvalidExtensionError, InvalidFieldError, InvalidIdentityError, InvalidModelError, InvalidModuleError, InvalidRelationError, InvalidTransitionError, InvalidUomError, MissingRateError, MissingRecordError, NoEnvironmentError, NonIntegerNumberError, NoRegistryError, RecomputeLimitError, ShutroError, type ShutroErrorCode, SingletonError, type SqlConstraintKind, TransactionScopeError, TransitionGuardError, UndeclaredDependencyError, UnknownModelError, UnknownSequenceError, UomMismatchError, ValidationError, } from './errors.js';
20
+ export type { CreateOf, FlagsOfField, ReadOf, WriteOf } from './model/faces.js';
21
+ export type { SequenceFieldOptions, TextWrite } from './model/field.js';
22
+ export { type BinaryField, type BinaryOptions, type CharField, type CharOptions, type CommonOptions, type ComputeFn, type DecimalField, type DecimalOptions, type Field, type FieldBase, type FieldBuilders, type FieldFlags, type FieldKind, type FieldOverrideChanges, type FieldTypes, type FlagsOf, type FloatField, f, type HtmlOptions, type IdField, type IndexKind, type InverseFn, isField, type JsonField, type JsonOptions, type Many2manyField, type Many2manyOptions, type Many2oneField, type Many2oneOptions, type MonetaryField, type MonetaryOptions, type OnDelete, type One2manyField, type QuantityField, type QuantityOptions, type ScalarField, type SelectionField, type SelectionOptions, type StateField, type StateHooks, type StateOptions, type StateSpec, type TextOptions, type Transition, type X2ManyOptions, } from './model/field.js';
23
+ export type * as F from './model/generated.js';
24
+ export { asId, type Id, type X2ManyCommands } from './model/id.js';
25
+ export type { OnchangeFn } from './model/model.js';
26
+ export { type ActiveField, type AnyModel, type CompanyField, type CompanyScope, type ConstraintSpec, defineModel, type FieldDescription, type FieldRules, type FieldsRecord, humanize, type ImplicitFields, type ImplicitFieldsBase, type IndexSpec, isModel, type MethodsRecord, type Model, type ModelDefinition, type ModelDescription, type ModelFields, type OrderSpec, type OrderTerm, RESERVED_KEYS, type ReservedKey, type ResolvedConstraint, type ResolvedIndex, type ResolvedSqlConstraint, type SqlCheckConstraint, type SqlUniqueConstraint, snakeCase, type TransitionMethods, transitionOf, } from './model/model.js';
27
+ export { type PartitionBound, type PartitionSpec, partitionStatements, rangePartitions, } from './model/partition.js';
28
+ export { type Currency, type CurrencyInput, defineCurrency, sameCurrency, } from './money/currency.js';
29
+ export { Decimal, type DecimalInput, toDecimal } from './money/decimal.js';
30
+ export type { Conversion, ConvertOptions, Fx, PreparedRates } from './money/fx.js';
31
+ export { Money, type MoneyJson } from './money/money.js';
32
+ export { defineUom, Quantity, type Uom, type UomInput } from './money/quantity.js';
33
+ export type { RoundingMethod } from './money/rounding.js';
34
+ export { coalesceAudit, isTracked } from './recordset/audit.js';
35
+ export { type JunctionTable, junctionTable } from './recordset/relations.js';
36
+ export { modelPolicies, rlsStatements, ruleCondition } from './recordset/rls.js';
37
+ export { UNNUMBERED } from './recordset/sequences.js';
38
+ export type { Access, ComputedKeys, ComputeRec, ComputeSet, CreateValues, DefaultLoaded, Defaults, Domain, Draft, DraftValue, FieldsOf, IdOnly, ListKeys, ListLoaded, LoadedKeys, LoadSpec, Many2oneKeys, Merge, MethodsOf, ModelName, ModelRef, NotLoaded, OnchangeInput, OnchangeResult, PendingSet, PlainRow, Rec, RecordSet, RecordSetApi, RelKeys, ScalarKeys, SearchOrder, SearchQuery, SequenceKeys, Target, ToLoaded, TranslatedKeys, WriteValues, X2ManyKeys, } from './recordset/types.js';
39
+ export { copyField } from './recordset/writes.js';
40
+ export { columnDefault, createTableStatements } from './registry/ddl.js';
41
+ export { type AnyExtension, type Extension, type ExtensionDefinition, extendModel, type FieldOverride, isExtension, type OverrideFn, type Replacement, replace, } from './registry/extension.js';
42
+ export { compareVersions, type DataMigration, defineModule, isModule, type MigrationContext, type Module, type ModuleBase, type ModuleDefinition, } from './registry/module.js';
43
+ export { buildRegistry, type MethodLayer, type Origin, type RegisteredModel, type Registry, type RegistryModelDescription, type RegistryOptions, type SchemaOfModule, type SchemaOfModules, targetOf, } from './registry/registry.js';
@@ -0,0 +1,34 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@shutro/core`: fields, `defineModel`, recordsets, environment, registry and compute engine (RFCs 0001–0004),
4
+ * and the accounting-safe value types of RFC 0006.
5
+ *
6
+ * Implemented so far: the value types (`Decimal`, `Money`, `Currency`, `Quantity`, `Uom`) and the environment &
7
+ * transaction context (`createShutro`, `Env`).
8
+ */
9
+ export { auditTableStatements, readTrail, } from '../audit/index.js';
10
+ export { isTranslations, mergeTranslation, resolveTranslation, } from '../i18n/index.js';
11
+ export { createKeyRing, defineGroup, EncryptionError, SecurityDefinitionError, } from '../security/index.js';
12
+ export { defineSequence, InvalidSequenceError, } from '../sequence/index.js';
13
+ export { buildComputeGraph, } from './compute/graph.js';
14
+ export { createShutro, Env, } from './env/env.js';
15
+ export { createInspector, } from './env/inspector.js';
16
+ export { assertTimeZone, calendarDateIn } from './env/time.js';
17
+ export { AccessError, CompanyNotAllowedError, ComputeAssignmentError, ComputeCycleError, ConcurrentUpdateError, ConstraintError, ConstraintViolationError, CrossCompanyError, CurrencyMismatchError, DivisionByZeroError, DuplicateModelError, DuplicateModuleError, EmptyMoneySumError, ExtensionConflictError, FieldNotLoadedError, FlagNotAllowedError, IncompatibleUomCategoryError, InvalidAllocationError, InvalidCurrencyError, InvalidDecimalError, InvalidDependsPathError, InvalidDomainError, InvalidExtensionError, InvalidFieldError, InvalidIdentityError, InvalidModelError, InvalidModuleError, InvalidRelationError, InvalidTransitionError, InvalidUomError, MissingRateError, MissingRecordError, NoEnvironmentError, NonIntegerNumberError, NoRegistryError, RecomputeLimitError, ShutroError, SingletonError, TransactionScopeError, TransitionGuardError, UndeclaredDependencyError, UnknownModelError, UnknownSequenceError, UomMismatchError, ValidationError, } from './errors.js';
18
+ export { f, isField, } from './model/field.js';
19
+ export { asId } from './model/id.js';
20
+ export { defineModel, humanize, isModel, RESERVED_KEYS, snakeCase, transitionOf, } from './model/model.js';
21
+ export { partitionStatements, rangePartitions, } from './model/partition.js';
22
+ export { defineCurrency, sameCurrency, } from './money/currency.js';
23
+ export { Decimal, toDecimal } from './money/decimal.js';
24
+ export { Money } from './money/money.js';
25
+ export { defineUom, Quantity } from './money/quantity.js';
26
+ export { coalesceAudit, isTracked } from './recordset/audit.js';
27
+ export { junctionTable } from './recordset/relations.js';
28
+ export { modelPolicies, rlsStatements, ruleCondition } from './recordset/rls.js';
29
+ export { UNNUMBERED } from './recordset/sequences.js';
30
+ export { copyField } from './recordset/writes.js';
31
+ export { columnDefault, createTableStatements } from './registry/ddl.js';
32
+ export { extendModel, isExtension, replace, } from './registry/extension.js';
33
+ export { compareVersions, defineModule, isModule, } from './registry/module.js';
34
+ export { buildRegistry, targetOf, } from './registry/registry.js';
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Multi-company consistency (RFC 0003 §7.4): a `checkCompany` many2one must point at a shared record (no company) or
3
+ * at a record of the referencing record's company. Synthesized as a business constraint by `defineModel`.
4
+ */
5
+ /** The check function of the synthesized `companyConsistency` constraint. Throws rather than returning failing records. */
6
+ export declare function companyConsistencyCheck(model: string, keys: readonly string[]): (records: never) => Promise<readonly never[]>;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Multi-company consistency (RFC 0003 §7.4): a `checkCompany` many2one must point at a shared record (no company) or
3
+ * at a record of the referencing record's company. Synthesized as a business constraint by `defineModel`.
4
+ */
5
+ import { CrossCompanyError } from '../errors.js';
6
+ /** The check function of the synthesized `companyConsistency` constraint. Throws rather than returning failing records. */
7
+ export function companyConsistencyCheck(model, keys) {
8
+ return async (records) => {
9
+ const set = records;
10
+ if (!set.env.flags.checkCompany)
11
+ return [];
12
+ const spec = {};
13
+ for (const key of keys)
14
+ spec[key] = ['company'];
15
+ const loaded = await set.load(spec);
16
+ const offending = [];
17
+ for (const record of loaded) {
18
+ const company = record.company?.id ?? null;
19
+ for (const key of keys) {
20
+ const target = record[key];
21
+ const targetCompany = target?.company?.id ?? null;
22
+ if (target === null || targetCompany === null || targetCompany === company)
23
+ continue;
24
+ offending.push({ id: record.id, field: key, company, targetCompany });
25
+ }
26
+ }
27
+ if (offending.length > 0)
28
+ throw new CrossCompanyError(model, offending);
29
+ return [];
30
+ };
31
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The three faces of a fields record (RFC 0001 §7.3):
3
+ * - `ReadOf`: what a record exposes. `T` when required, else `T | null`. Null is the only empty value.
4
+ * - `CreateOf`: what `create()` accepts. Readonly and computed fields are absent; required fields without a
5
+ * default are mandatory; everything else is optional.
6
+ * - `WriteOf`: what `write()` accepts. Same exclusions, all optional.
7
+ */
8
+ import type { FieldFlags, FieldTypes } from './field.js';
9
+ type TypesOf<F> = F extends {
10
+ readonly '~types'?: infer T;
11
+ } ? NonNullable<T> : never;
12
+ /** The phantom flags of a field descriptor. */
13
+ export type FlagsOfField<F> = TypesOf<F> extends FieldTypes<unknown, unknown, infer Fl> ? Fl : FieldFlags;
14
+ type Read<F> = TypesOf<F> extends FieldTypes<infer R, unknown, FieldFlags> ? R : never;
15
+ type Write<F> = TypesOf<F> extends FieldTypes<unknown, infer W, FieldFlags> ? W : never;
16
+ type Required<F> = FlagsOfField<F>['required'] extends true ? true : false;
17
+ type Writable<F> = FlagsOfField<F>['readonly'] extends true ? false : true;
18
+ type Mandatory<F> = Required<F> extends true ? FlagsOfField<F>['hasDefault'] extends true ? false : FlagsOfField<F>['sequence'] extends true ? false : FlagsOfField<F>['computed'] extends true ? false : true : false;
19
+ type WriteValue<F> = Required<F> extends true ? Write<F> : Write<F> | null;
20
+ /** Flattens an intersection into one object type (readable hovers and exact `toEqualTypeOf`). */
21
+ type Simplify<T> = {
22
+ [K in keyof T]: T[K];
23
+ } & NonNullable<unknown>;
24
+ /** The read face of a fields record. */
25
+ export type ReadOf<Fs> = {
26
+ readonly [K in keyof Fs]: Required<Fs[K]> extends true ? Read<Fs[K]> : Read<Fs[K]> | null;
27
+ };
28
+ /** The create face of a fields record. */
29
+ export type CreateOf<Fs> = Simplify<{
30
+ readonly [K in keyof Fs as Writable<Fs[K]> extends true ? Mandatory<Fs[K]> extends true ? K : never : never]: WriteValue<Fs[K]>;
31
+ } & {
32
+ readonly [K in keyof Fs as Writable<Fs[K]> extends true ? Mandatory<Fs[K]> extends true ? never : K : never]?: WriteValue<Fs[K]>;
33
+ }>;
34
+ /** The write face of a fields record. */
35
+ export type WriteOf<Fs> = {
36
+ readonly [K in keyof Fs as Writable<Fs[K]> extends true ? K : never]?: WriteValue<Fs[K]>;
37
+ };
38
+ /** The value a record exposes for field `F`: `T` when required, else `T | null`. */
39
+ export type ReadValue<F> = Required<F> extends true ? Read<F> : Read<F> | null;
40
+ /** The write type of field `F` (what `create` / `write` / domains accept). */
41
+ export type WriteType<F> = Write<F>;
42
+ export {};
@@ -0,0 +1 @@
1
+ export {};