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,77 @@
1
+ /**
2
+ * Running a state transition (RFC 0010 §7.2): validate the source states, run the guard, run the events, write the
3
+ * state through the unit of work.
4
+ */
5
+ import { InvalidTransitionError, TransitionGuardError } from '../errors.js';
6
+ import { trackChange } from './audit.js';
7
+ import { failingIds } from './constraints.js';
8
+ import { assertAccess, assertRecords } from './security.js';
9
+ /** Runs transition `name` of state field `key` on `ids` of `model`. */
10
+ export async function runTransition(host, model, ids, key, name) {
11
+ if (ids.length === 0)
12
+ return;
13
+ const { internals } = host;
14
+ assertAccess(internals, model, 'write');
15
+ await assertRecords(internals, model, ids, 'write');
16
+ const field = model.fields[key];
17
+ const transition = field.transitions[name];
18
+ if (transition === undefined)
19
+ throw new InvalidTransitionError(model.name, name, [], []);
20
+ await host.load(model, ids, { fields: new Set(['id', key]), relations: new Map() });
21
+ const stateOf = (id) => String(host.values(model.name, id)?.get(key));
22
+ const invalid = ids.filter((id) => !transition.from.includes(stateOf(id)));
23
+ if (invalid.length > 0) {
24
+ throw new InvalidTransitionError(model.name, name, invalid.map((id) => ({ id, state: stateOf(id) })), transition.from);
25
+ }
26
+ const records = host.recordset(model, ids);
27
+ const guard = transition.guard;
28
+ if (guard !== undefined) {
29
+ const failing = failingIds(await guard.call(records, records));
30
+ if (failing.length > 0) {
31
+ throw new TransitionGuardError(model.name, name, failing, transition.message ?? `${failing.length} record(s) do not satisfy the guard of '${name}'.`);
32
+ }
33
+ }
34
+ const byState = new Map();
35
+ for (const id of ids)
36
+ byState.set(stateOf(id), [...(byState.get(stateOf(id)) ?? []), id]);
37
+ for (const [state, group] of byState) {
38
+ const onExit = field.stateHooks[state]?.onExit;
39
+ if (onExit !== undefined) {
40
+ const set = host.recordset(model, group);
41
+ await onExit.call(set, set);
42
+ }
43
+ }
44
+ const before = transition.before;
45
+ if (before !== undefined)
46
+ await before.call(records, records);
47
+ // The state write: cache, journal, dirty, triggers (RFC 0008 §7.2). The field is readonly for write(); this is the one path that sets it.
48
+ for (const id of ids) {
49
+ const values = host.values(model.name, id, true);
50
+ internals.journal({
51
+ kind: 'value',
52
+ model: model.name,
53
+ id,
54
+ key,
55
+ had: values.has(key),
56
+ prev: values.get(key),
57
+ wasDirty: internals.isDirty(model.name, id, key),
58
+ });
59
+ trackChange(internals, model, id, key, values.get(key), transition.to, (k) => values.get(k));
60
+ values.set(key, transition.to);
61
+ internals.markDirty(model.name, id, key);
62
+ }
63
+ internals.trigger(model.name, key, ids);
64
+ const after = transition.after;
65
+ if (after !== undefined)
66
+ await after.call(records, records);
67
+ const onEnter = field.stateHooks[transition.to]?.onEnter;
68
+ if (onEnter !== undefined)
69
+ await onEnter.call(records, records);
70
+ }
71
+ /** Transition names available from the current state of one record (state must be loaded). */
72
+ export function availableTransitions(model, key, state) {
73
+ const field = model.fields[key];
74
+ return Object.entries(field.transitions)
75
+ .filter(([, t]) => t.from.includes(String(state)))
76
+ .map(([n]) => n);
77
+ }
@@ -0,0 +1,296 @@
1
+ /**
2
+ * Recordset types (RFC 0004 §7.2): the loaded shape `L` of a recordset is tracked in the types, so reading a field
3
+ * that was not loaded is a compile error whose message says which `load()` is missing.
4
+ *
5
+ * Shapes are `{ s: <loaded field keys>; r: { <relation>: <shape> } }` and are read through `infer` helpers
6
+ * (spike 0001, lesson 2).
7
+ */
8
+ import type { AuditAction, AuditEntry } from '../../audit/index.js';
9
+ import type { Translations } from '../../i18n/index.js';
10
+ import type { Env } from '../env/env.js';
11
+ import type { CreateOf, FlagsOfField, ReadValue, WriteOf, WriteType } from '../model/faces.js';
12
+ import type { Id, X2ManyCommands } from '../model/id.js';
13
+ import type { Decimal } from '../money/decimal.js';
14
+ import type { MoneyJson } from '../money/money.js';
15
+ /** Model names of a schema view. */
16
+ export type ModelName<S> = keyof S & string;
17
+ /** Fields of model `M`. */
18
+ export type FieldsOf<S, M extends ModelName<S>> = S[M] extends {
19
+ readonly fields: infer F;
20
+ } ? F : never;
21
+ type KindOf<F> = F extends {
22
+ readonly kind: infer K extends string;
23
+ } ? K : never;
24
+ type TargetOf<F> = F extends {
25
+ readonly target: infer T extends string;
26
+ } ? T : never;
27
+ /** Target model of relation field `K` of `M`. */
28
+ export type Target<S, M extends ModelName<S>, K> = K extends keyof FieldsOf<S, M> ? TargetOf<FieldsOf<S, M>[K]> & ModelName<S> : never;
29
+ type IsX2Many<F> = KindOf<F> extends 'one2many' | 'many2many' ? true : false;
30
+ type IsRelation<F> = KindOf<F> extends 'many2one' | 'one2many' | 'many2many' ? true : false;
31
+ type IsDefault<F> = IsX2Many<F> extends true ? false : KindOf<F> extends 'binary' ? false : FlagsOfField<F>['computed'] extends true ? FlagsOfField<F>['store'] extends true ? true : false : true;
32
+ type Keys<S, M extends ModelName<S>> = keyof FieldsOf<S, M> & string;
33
+ /** Fields `search()` / `browse().load()` load by default: stored, non-binary, not x2many. */
34
+ export type Defaults<S, M extends ModelName<S>> = {
35
+ [K in Keys<S, M>]: IsDefault<FieldsOf<S, M>[K]> extends true ? K : never;
36
+ }[Keys<S, M>];
37
+ /** Relation field keys. */
38
+ export type RelKeys<S, M extends ModelName<S>> = {
39
+ [K in Keys<S, M>]: IsRelation<FieldsOf<S, M>[K]> extends true ? K : never;
40
+ }[Keys<S, M>];
41
+ /** Keys that can appear in a list load spec: everything but x2many. */
42
+ export type ListKeys<S, M extends ModelName<S>> = {
43
+ [K in Keys<S, M>]: IsX2Many<FieldsOf<S, M>[K]> extends true ? never : K;
44
+ }[Keys<S, M>];
45
+ /** Non-relational keys. */
46
+ export type ScalarKeys<S, M extends ModelName<S>> = {
47
+ [K in Keys<S, M>]: IsRelation<FieldsOf<S, M>[K]> extends true ? never : K;
48
+ }[Keys<S, M>];
49
+ type NoRels = Record<never, never>;
50
+ type SOf<L> = L extends {
51
+ readonly s: infer X extends string;
52
+ } ? X : never;
53
+ type ROf<L> = L extends {
54
+ readonly r: infer X;
55
+ } ? X : NoRels;
56
+ /** What `search()` and `browse().load()` load. */
57
+ export type DefaultLoaded<S, M extends ModelName<S>> = {
58
+ readonly s: Defaults<S, M>;
59
+ readonly r: NoRels;
60
+ };
61
+ /** Exactly the listed keys (plus `id`). */
62
+ export type ListLoaded<K extends string> = {
63
+ readonly s: K | 'id';
64
+ readonly r: NoRels;
65
+ };
66
+ type Dec = [0, 0, 1, 2, 3];
67
+ /** The `load()` argument: relation keys mapped to `true`, a key list, or a nested spec (depth ≤ 4). */
68
+ export type LoadSpec<S, M extends ModelName<S>, D extends number = 4> = {
69
+ readonly [K in RelKeys<S, M>]?: true | readonly ListKeys<S, Target<S, M, K>>[] | (D extends 0 ? never : LoadSpec<S, Target<S, M, K>, Dec[D]>);
70
+ };
71
+ /** Converts a spec into a loaded shape. A nested object loads the relation's defaults plus its nested relations. */
72
+ export type ToLoaded<S, M extends ModelName<S>, X> = X extends true ? DefaultLoaded<S, M> : X extends readonly (infer K extends string)[] ? ListLoaded<K> : {
73
+ readonly s: Defaults<S, M>;
74
+ readonly r: {
75
+ readonly [K in keyof X & RelKeys<S, M>]: ToLoaded<S, Target<S, M, K>, X[K]>;
76
+ };
77
+ };
78
+ /** Union of two loaded shapes, recursively. */
79
+ export type Merge<A, B> = {
80
+ readonly s: SOf<A> | SOf<B>;
81
+ readonly r: {
82
+ readonly [K in keyof ROf<A> | keyof ROf<B>]: K extends keyof ROf<A> ? K extends keyof ROf<B> ? Merge<ROf<A>[K], ROf<B>[K]> : ROf<A>[K] : K extends keyof ROf<B> ? ROf<B>[K] : never;
83
+ };
84
+ };
85
+ /** Branded error type: using it where a value is expected shows the fix in the message. */
86
+ export interface NotLoaded<M extends string, K extends string> {
87
+ readonly __notLoaded: `${M}.${K} is not loaded: add it to .load({ ... })`;
88
+ }
89
+ /** A many2one that was not loaded: only its id is known. */
90
+ export interface IdOnly<M extends string> {
91
+ readonly id: Id<M>;
92
+ readonly modelName: M;
93
+ }
94
+ type Req<V, F> = FlagsOfField<F>['required'] extends true ? V : V | null;
95
+ type FieldValue<S, M extends ModelName<S>, K extends string, F, L> = IsX2Many<F> extends true ? K extends keyof ROf<L> ? RecordSet<S, Target<S, M, K>, ROf<L>[K]> : PendingSet<S, Target<S, M, K>> : KindOf<F> extends 'many2one' ? K extends keyof ROf<L> ? Req<Rec<S, Target<S, M, K>, ROf<L>[K]>, F> : K extends SOf<L> ? Req<IdOnly<Target<S, M, K>>, F> : NotLoaded<M, K> : K extends SOf<L> ? ReadValue<F> : NotLoaded<M, K>;
96
+ /** Field access on a single record. */
97
+ export type Access<S, M extends ModelName<S>, L> = {
98
+ readonly [K in Keys<S, M>]: FieldValue<S, M, K, FieldsOf<S, M>[K], L>;
99
+ };
100
+ /** A singleton: a recordset of one plus field access. */
101
+ export type Rec<S, M extends ModelName<S>, L> = RecordSet<S, M, L> & Access<S, M, L>;
102
+ type PlainValue<S, M extends ModelName<S>, K extends string, F> = IsX2Many<F> extends true ? readonly Id<Target<S, M, K>>[] : KindOf<F> extends 'many2one' ? Req<Id<Target<S, M, K>>, F> : KindOf<F> extends 'monetary' ? Req<MoneyJson, F> : KindOf<F> extends 'quantity' ? Req<{
103
+ readonly value: string;
104
+ readonly uom: string;
105
+ }, F> : KindOf<F> extends 'datetime' ? Req<string, F> : KindOf<F> extends 'decimal' ? Req<string, F> : ReadValue<F>;
106
+ /** Plain, JSON-serializable rows as `read()` returns them. */
107
+ export type PlainRow<S, M extends ModelName<S>, K extends string> = {
108
+ readonly id: Id<M>;
109
+ } & {
110
+ readonly [X in K]: PlainValue<S, M, X, X extends keyof FieldsOf<S, M> ? FieldsOf<S, M>[X] : never>;
111
+ };
112
+ /** Keys readable from a shape: loaded scalars/many2one ids and loaded relations. */
113
+ export type LoadedKeys<L> = SOf<L> | (keyof ROf<L> & string);
114
+ /** An x2many reached without loading it: navigable, but no synchronous data. */
115
+ export interface PendingSet<S, M extends ModelName<S>> {
116
+ readonly modelName: M;
117
+ /** Loads the defaults for every record of the prefetch group. */
118
+ load(): Promise<RecordSet<S, M, DefaultLoaded<S, M>>>;
119
+ load<const K extends readonly ListKeys<S, M>[]>(keys: K): Promise<RecordSet<S, M, ListLoaded<K[number]>>>;
120
+ load<const X extends LoadSpec<S, M>>(spec: X): Promise<RecordSet<S, M, Merge<DefaultLoaded<S, M>, ToLoaded<S, M, X>>>>;
121
+ ids(): Promise<readonly Id<M>[]>;
122
+ }
123
+ /** An ordered, immutable set of records of one model, bound to an environment (RFC 0004). */
124
+ export interface RecordSetApi<S, M extends ModelName<S>, L> {
125
+ readonly env: Env<S>;
126
+ readonly modelName: M;
127
+ readonly ids: readonly Id<M>[];
128
+ readonly length: number;
129
+ [Symbol.iterator](): Iterator<Rec<S, M, L>>;
130
+ /** @throws {SingletonError} when empty */
131
+ first(): Rec<S, M, L>;
132
+ /** @throws {SingletonError} unless exactly one record */
133
+ ensureOne(): Rec<S, M, L>;
134
+ isEmpty(): boolean;
135
+ load(): Promise<RecordSet<S, M, Merge<L, DefaultLoaded<S, M>>>>;
136
+ load<const K extends readonly ListKeys<S, M>[]>(keys: K): Promise<RecordSet<S, M, Merge<L, ListLoaded<K[number]>>>>;
137
+ load<const X extends LoadSpec<S, M>>(spec: X): Promise<RecordSet<S, M, Merge<L, ToLoaded<S, M, X>>>>;
138
+ map<T>(fn: (record: Rec<S, M, L>, index: number) => T): T[];
139
+ filter(fn: (record: Rec<S, M, L>, index: number) => boolean): RecordSet<S, M, L>;
140
+ /** The values of a loaded scalar field, in order. */
141
+ mapped<K extends ScalarKeys<S, M> & SOf<L>>(key: K): ReadValue<FieldsOf<S, M>[K]>[];
142
+ /** Updates the records in the cache now; the database is updated at the next flush point (search, raw SQL, savepoint end, commit). */
143
+ write(values: WriteValues<S, M>): Promise<void>;
144
+ /** Deletes the records now (`ON DELETE` rules apply). */
145
+ unlink(): Promise<void>;
146
+ /** Plain JSON rows (ids for relations, `Money` / `Quantity` as objects, dates as ISO strings). */
147
+ read<const K extends readonly LoadedKeys<L>[]>(keys: K): PlainRow<S, M, K[number]>[];
148
+ /** The audit rows of these records, newest first (RFC 0013 §7.4). */
149
+ trail(options?: {
150
+ readonly field?: Keys<S, M>;
151
+ readonly limit?: number;
152
+ readonly action?: AuditAction;
153
+ }): Promise<readonly AuditEntry[]>;
154
+ /** Numbers these records from their manual sequence (RFC 0012 §7.4); records with a number are refused. */
155
+ assignNumber<K extends SequenceKeys<S, M>>(key: K, options?: {
156
+ readonly date?: string;
157
+ }): Promise<void>;
158
+ /** The full translation map of a translatable field (singleton, loaded), or `null` (RFC 0011). */
159
+ translations<K extends TranslatedKeys<S, M>>(key: K): Translations | null;
160
+ /** Transition names the current state allows (singleton with its state loaded; RFC 0010 §7.3). */
161
+ transitions(): readonly string[];
162
+ toJSON(): readonly Id<M>[];
163
+ }
164
+ /** The model's methods (declared ones and generated transitions), callable on recordsets. */
165
+ export type MethodsOf<S, M extends ModelName<S>> = S[M] extends {
166
+ readonly methods: infer Ms;
167
+ } ? Ms : NonNullable<unknown>;
168
+ /** An ordered, immutable set of records of one model, with the model's methods (RFC 0004, RFC 0010 §7.6). */
169
+ export type RecordSet<S, M extends ModelName<S>, L> = RecordSetApi<S, M, L> & MethodsOf<S, M>;
170
+ type DomainKeys<S, M extends ModelName<S>> = ListKeys<S, M>;
171
+ type DomainOperators<V> = {
172
+ readonly eq?: V | null;
173
+ readonly ne?: V | null;
174
+ readonly lt?: V;
175
+ readonly lte?: V;
176
+ readonly gt?: V;
177
+ readonly gte?: V;
178
+ readonly in?: readonly V[];
179
+ readonly notIn?: readonly V[];
180
+ readonly isNull?: boolean;
181
+ readonly like?: string;
182
+ readonly ilike?: string;
183
+ };
184
+ type DomainValue<F> = WriteType<F> extends never ? unknown : WriteType<F> | DomainOperators<WriteType<F>>;
185
+ /** A search filter: field → value (equality) or operators. Keys are ANDed. Relation paths come with the domain compiler. */
186
+ export type Domain<S, M extends ModelName<S>> = {
187
+ readonly [K in DomainKeys<S, M>]?: K extends 'id' ? Id<M> | DomainOperators<Id<M>> : DomainValue<FieldsOf<S, M>[K]>;
188
+ } & {
189
+ /** Records with at least one / no related record matching the domain. */
190
+ readonly [K in X2ManyKeys<S, M>]?: {
191
+ readonly any?: Domain<S, Target<S, M, K>>;
192
+ readonly none?: Domain<S, Target<S, M, K>>;
193
+ };
194
+ } & {
195
+ /** Any of the domains. */
196
+ readonly or?: readonly Domain<S, M>[];
197
+ readonly and?: readonly Domain<S, M>[];
198
+ readonly not?: Domain<S, M>;
199
+ /** A relation path such as `'partner.name'` (checked at runtime; typed paths come with the generator). */
200
+ readonly [path: `${string}.${string}`]: unknown;
201
+ };
202
+ /** `'field'`, `'field asc'` or `'field desc'` over sortable (non-x2many) fields. */
203
+ export type SearchOrder<S, M extends ModelName<S>> = ListKeys<S, M> | `${ListKeys<S, M>} asc` | `${ListKeys<S, M>} desc`;
204
+ /** Argument of `search()`. */
205
+ export interface SearchQuery<S, M extends ModelName<S>> {
206
+ readonly where?: Domain<S, M>;
207
+ readonly order?: readonly SearchOrder<S, M>[];
208
+ readonly limit?: number;
209
+ readonly offset?: number;
210
+ }
211
+ /** Values accepted by `create()`: the create face of the model's fields (x2many fields take commands). */
212
+ export type CreateValues<S, M extends ModelName<S>> = CreateOf<FieldsOf<S, M>>;
213
+ /** Values accepted by `write()`. */
214
+ export type WriteValues<S, M extends ModelName<S>> = WriteOf<FieldsOf<S, M>>;
215
+ /** `env.model(name)`: the entry point for a model. */
216
+ export interface ModelRef<S, M extends ModelName<S>> {
217
+ readonly modelName: M;
218
+ /** Inserts records (one statement per model) and returns them with their defaults loaded (RFC 0004 §7.6). */
219
+ create(values: readonly CreateValues<S, M>[]): Promise<RecordSet<S, M, DefaultLoaded<S, M>>>;
220
+ search(query?: SearchQuery<S, M>): Promise<RecordSet<S, M, DefaultLoaded<S, M>>>;
221
+ /** A lazy recordset of these ids. Nothing is fetched until `load()`. */
222
+ browse(ids: readonly number[]): PendingSet<S, M>;
223
+ /** Form assist on an in-memory draft: derived values and warnings, nothing written (RFC 0009 §7.4). */
224
+ onchange(input: OnchangeInput<S, M>): Promise<OnchangeResult<S, M>>;
225
+ /**
226
+ * Bulk create through PostgreSQL COPY (RFC 0015 §7.1): the same semantics as create() (defaults, sequences,
227
+ * computes, constraints, audit, rules), one streamed statement instead of 1,000-row INSERTs. Needs the `import`
228
+ * permission. x2many commands are not accepted.
229
+ */
230
+ copy(values: readonly CreateValues<S, M>[]): Promise<RecordSet<S, M, DefaultLoaded<S, M>>>;
231
+ }
232
+ /** Keys of sequence-numbered fields. */
233
+ export type SequenceKeys<S, M extends ModelName<S>> = {
234
+ [K in Keys<S, M>]: FlagsOfField<FieldsOf<S, M>[K]>['sequence'] extends true ? K : never;
235
+ }[Keys<S, M>];
236
+ /** Keys of translatable text fields (their write type accepts a translation map). */
237
+ export type TranslatedKeys<S, M extends ModelName<S>> = {
238
+ [K in Keys<S, M>]: Translations extends WriteType<FieldsOf<S, M>[K]> ? K : never;
239
+ }[Keys<S, M>];
240
+ /** Keys of computed fields. */
241
+ export type ComputedKeys<S, M extends ModelName<S>> = {
242
+ [K in Keys<S, M>]: FlagsOfField<FieldsOf<S, M>[K]>['computed'] extends true ? K : never;
243
+ }[Keys<S, M>];
244
+ /** A record inside a compute: computed keys are assignable (RFC 0008 §7.7). */
245
+ export type ComputeRec<S, M extends ModelName<S>, L> = Omit<Rec<S, M, L>, ComputedKeys<S, M>> & {
246
+ -readonly [K in ComputedKeys<S, M>]: FieldValue<S, M, K, FieldsOf<S, M>[K], L> | WriteType<FieldsOf<S, M>[K]>;
247
+ };
248
+ /** A recordset inside a compute: iteration yields {@link ComputeRec}. */
249
+ export type ComputeSet<S, M extends ModelName<S>, L> = Omit<RecordSet<S, M, L>, typeof Symbol.iterator | 'first' | 'ensureOne'> & {
250
+ [Symbol.iterator](): Iterator<ComputeRec<S, M, L>>;
251
+ first(): ComputeRec<S, M, L>;
252
+ ensureOne(): ComputeRec<S, M, L>;
253
+ };
254
+ /** Many2one keys. */
255
+ export type Many2oneKeys<S, M extends ModelName<S>> = {
256
+ [K in Keys<S, M>]: KindOf<FieldsOf<S, M>[K]> extends 'many2one' ? K : never;
257
+ }[Keys<S, M>];
258
+ /** x2many keys. */
259
+ export type X2ManyKeys<S, M extends ModelName<S>> = {
260
+ [K in Keys<S, M>]: IsX2Many<FieldsOf<S, M>[K]> extends true ? K : never;
261
+ }[Keys<S, M>];
262
+ /** What a draft holds for a field: an id for many2one, commands for x2many, a Decimal for amounts, read values otherwise. */
263
+ export type DraftValue<S, M extends ModelName<S>, K extends Keys<S, M>> = IsX2Many<FieldsOf<S, M>[K]> extends true ? X2ManyCommands<Target<S, M, K>> | undefined : KindOf<FieldsOf<S, M>[K]> extends 'many2one' ? Id<Target<S, M, K>> | null : KindOf<FieldsOf<S, M>[K]> extends 'monetary' | 'quantity' ? Decimal | null : ReadValue<FieldsOf<S, M>[K]> | null;
264
+ /** The draft an onchange handler receives (RFC 0009 §7.3). */
265
+ export interface Draft<S, M extends ModelName<S>> {
266
+ readonly id: Id<M> | null;
267
+ readonly env: Env<S>;
268
+ get<K extends Keys<S, M>>(key: K): DraftValue<S, M, K>;
269
+ /** Normalized like a write; `null` is always accepted in a draft. Marks the key changed (its handler runs next). */
270
+ set<K extends Keys<S, M>>(key: K, value: WriteType<FieldsOf<S, M>[K]> | null): void;
271
+ /** The related record of a many2one, loaded with its defaults, or null. */
272
+ record<K extends Many2oneKeys<S, M>>(key: K): Promise<Rec<S, Target<S, M, K>, DefaultLoaded<S, Target<S, M, K>>> | null>;
273
+ warn(message: string): void;
274
+ }
275
+ /** The input of `env.model(M).onchange()`. */
276
+ export interface OnchangeInput<S, M extends ModelName<S>> {
277
+ /** An existing record: its values are the base of the draft. */
278
+ readonly id?: Id<M> | undefined;
279
+ /** The form's values (x2many as commands; `create` rows become virtual children). */
280
+ readonly values: {
281
+ readonly [K in Keys<S, M>]?: WriteType<FieldsOf<S, M>[K]> | null;
282
+ };
283
+ /** Fields whose handlers run, in order. */
284
+ readonly changed: readonly Keys<S, M>[];
285
+ }
286
+ /** The output of `env.model(M).onchange()`. */
287
+ export interface OnchangeResult<S, M extends ModelName<S>> {
288
+ /** Scalar and many2one fields whose plain value differs from the input. */
289
+ readonly values: Partial<PlainRow<S, M, Exclude<ScalarKeys<S, M> | Many2oneKeys<S, M>, 'id'>>>;
290
+ readonly warnings: readonly string[];
291
+ /** Plain rows of the virtual children created by `create` commands, per x2many field. */
292
+ readonly children: {
293
+ readonly [K in X2ManyKeys<S, M>]?: readonly Record<string, unknown>[];
294
+ };
295
+ }
296
+ export {};
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Recordset types (RFC 0004 §7.2): the loaded shape `L` of a recordset is tracked in the types, so reading a field
3
+ * that was not loaded is a compile error whose message says which `load()` is missing.
4
+ *
5
+ * Shapes are `{ s: <loaded field keys>; r: { <relation>: <shape> } }` and are read through `infer` helpers
6
+ * (spike 0001, lesson 2).
7
+ */
8
+ export {};
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Value normalization shared by writes and computes: validates one value against its field and converts it to what
3
+ * the cache holds (Decimal amounts, ids, ...), and converts cached values into what the driver binds.
4
+ */
5
+ import { type SqlFragment } from '../../sql/index.js';
6
+ /** The environment language and the source language, for translatable values (RFC 0011). */
7
+ export interface TranslationContext {
8
+ readonly lang: string;
9
+ readonly source: string;
10
+ }
11
+ import type { Field } from '../model/field.js';
12
+ import type { AnyModel } from '../model/model.js';
13
+ /** Throws a {@link ValidationError} for `model`. */
14
+ export declare function fail(model: AnyModel, fields: readonly string[], problem: string, hint: string): never;
15
+ /** The PostgreSQL array element type for a field (for `unnest($n::type[])`). */
16
+ export declare function arrayType(field: Field): string;
17
+ /** The SQL cast applied to a bound value before it reaches the column (`jsonb` for json and translatable fields). */
18
+ export declare function columnCast(field: Field): 'jsonb' | undefined;
19
+ /** A reference to the bound value of `column` in the `v` row alias, cast when needed. */
20
+ export declare function valueRef(field: Field, column: string): SqlFragment;
21
+ /** Converts a cached value into what the driver binds. */
22
+ export declare function bindValue(field: Field, value: unknown): unknown;
23
+ /**
24
+ * Validates and normalizes one value for storage in the cache. `siblings` gives the record's current currency / unit
25
+ * id for `Money` / `Quantity` checks.
26
+ */
27
+ export declare function normalize(model: AnyModel, key: string, field: Field, value: unknown, siblings: (key: string) => unknown, translation?: TranslationContext): unknown;
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Value normalization shared by writes and computes: validates one value against its field and converts it to what
3
+ * the cache holds (Decimal amounts, ids, ...), and converts cached values into what the driver binds.
4
+ */
5
+ import { isTranslations, mergeTranslation } from '../../i18n/index.js';
6
+ import { sql } from '../../sql/index.js';
7
+ import { Decimal as DecimalJs } from 'decimal.js';
8
+ import { CurrencyMismatchError, UomMismatchError, ValidationError } from '../errors.js';
9
+ import { toDecimal } from '../money/decimal.js';
10
+ import { Money } from '../money/money.js';
11
+ import { Quantity } from '../money/quantity.js';
12
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
13
+ /** Throws a {@link ValidationError} for `model`. */
14
+ export function fail(model, fields, problem, hint) {
15
+ throw new ValidationError(model.name, fields, problem, hint);
16
+ }
17
+ /** The PostgreSQL array element type for a field (for `unnest($n::type[])`). */
18
+ export function arrayType(field) {
19
+ if (field.kind === 'many2one')
20
+ return 'bigint';
21
+ // JSON travels as text and is cast in SQL (columnCast): array parameters of jsonb would be re-encoded by the driver.
22
+ if (columnCast(field) !== undefined)
23
+ return 'text';
24
+ return field.pgType;
25
+ }
26
+ /** The SQL cast applied to a bound value before it reaches the column (`jsonb` for json and translatable fields). */
27
+ export function columnCast(field) {
28
+ return field.kind === 'json' || field.translate ? 'jsonb' : undefined;
29
+ }
30
+ /** A reference to the bound value of `column` in the `v` row alias, cast when needed. */
31
+ export function valueRef(field, column) {
32
+ const ref = sql.id('v', column);
33
+ return columnCast(field) === undefined ? ref : sql `${ref}::jsonb`;
34
+ }
35
+ /** Converts a cached value into what the driver binds. */
36
+ export function bindValue(field, value) {
37
+ if (value === null || value === undefined)
38
+ return null;
39
+ if (DecimalJs.isDecimal(value))
40
+ return value.toFixed();
41
+ // Inside arrays, postgres.js would type a Date as a scalar timestamptz; an ISO string lets the ::timestamptz[] cast apply.
42
+ if (value instanceof Date)
43
+ return value.toISOString();
44
+ if (field.kind === 'json' || field.translate)
45
+ return JSON.stringify(value);
46
+ return value;
47
+ }
48
+ /**
49
+ * Validates and normalizes one value for storage in the cache. `siblings` gives the record's current currency / unit
50
+ * id for `Money` / `Quantity` checks.
51
+ */
52
+ export function normalize(model, key, field, value, siblings, translation) {
53
+ const bad = (what, hint) => fail(model, [key], `field '${key}' ${what}.`, hint);
54
+ if (value === null) {
55
+ if (field.required)
56
+ bad('is required and cannot be null', 'Give the field a value.');
57
+ return null;
58
+ }
59
+ switch (field.kind) {
60
+ case 'many2one': {
61
+ if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0)
62
+ return value;
63
+ const ids = value.ids;
64
+ if (Array.isArray(ids) && ids.length === 1)
65
+ return ids[0];
66
+ return bad(`expects a record id (got ${typeof value})`, 'Pass the id of the related record, or a single record.');
67
+ }
68
+ case 'monetary': {
69
+ if (value instanceof Money) {
70
+ const currencyId = siblings(field.currencyField);
71
+ if (typeof currencyId !== 'number') {
72
+ bad("is given as Money but the record's currency is not known", 'Load the currency field first, or write a Decimal / string amount.');
73
+ }
74
+ if (value.currency.id !== currencyId) {
75
+ throw new CurrencyMismatchError(`Cannot write ${value.toString()} to ${model.name}.${key}: the record's currency is a different one (id ${String(currencyId)}).`, "Convert the amount to the record's currency first (env.fx.convert with the document date), or write the record's currency field in the same write.");
76
+ }
77
+ return value.amount;
78
+ }
79
+ return decimalOf(model, key, value);
80
+ }
81
+ case 'quantity': {
82
+ if (value instanceof Quantity) {
83
+ const uomId = siblings(field.uomField);
84
+ if (value.uom.id !== uomId) {
85
+ throw new UomMismatchError(`Cannot write ${value.toString()} to ${model.name}.${key}: the record's unit is a different one (id ${String(uomId)}).`, "Convert the quantity with .to(uom) first, or write the record's unit field in the same write.");
86
+ }
87
+ return value.value;
88
+ }
89
+ return decimalOf(model, key, value);
90
+ }
91
+ case 'decimal':
92
+ return decimalOf(model, key, value);
93
+ case 'integer':
94
+ return typeof value === 'number' && Number.isSafeInteger(value)
95
+ ? value
96
+ : bad('expects an integer', 'Pass a safe integer number.');
97
+ case 'bigint':
98
+ return typeof value === 'bigint' || (typeof value === 'number' && Number.isSafeInteger(value))
99
+ ? value
100
+ : bad('expects an integer', 'Pass a bigint or a safe integer.');
101
+ case 'boolean':
102
+ return typeof value === 'boolean' ? value : bad('expects true or false', 'Pass a boolean.');
103
+ case 'char':
104
+ case 'text':
105
+ case 'html': {
106
+ if (field.translate) {
107
+ if (typeof value !== 'string' && !isTranslations(value))
108
+ return bad('expects a string or a { lang: text } map', "Pass 'text' (written in the environment language) or { en_US: 'text', bn_BD: '...' }.");
109
+ const ctx = translation ?? { lang: 'en_US', source: 'en_US' };
110
+ const existing = siblings(key);
111
+ return mergeTranslation(isTranslations(existing) ? existing : null, value, ctx.lang, ctx.source);
112
+ }
113
+ return typeof value === 'string' ? value : bad('expects a string', 'Pass a string.');
114
+ }
115
+ case 'date':
116
+ return typeof value === 'string' && DATE.test(value)
117
+ ? value
118
+ : bad("expects a 'YYYY-MM-DD' string", "Pass a calendar date such as '2026-10-15', never a JS Date.");
119
+ case 'datetime':
120
+ return value instanceof Date && !Number.isNaN(value.getTime())
121
+ ? value
122
+ : bad('expects a Date', 'Pass a valid JS Date (stored in UTC).');
123
+ case 'selection':
124
+ case 'state': {
125
+ const selection = field.selection;
126
+ const allowed = typeof selection === 'function' ? selection() : selection.map(([k]) => k);
127
+ return typeof value === 'string' && allowed.includes(value)
128
+ ? value
129
+ : bad(`expects one of ${allowed.join(', ')}`, `Got ${JSON.stringify(value)}.`);
130
+ }
131
+ case 'binary':
132
+ return value instanceof Uint8Array ? value : bad('expects bytes', 'Pass a Uint8Array.');
133
+ default:
134
+ return value;
135
+ }
136
+ }
137
+ function decimalOf(model, key, value) {
138
+ try {
139
+ return toDecimal(value);
140
+ }
141
+ catch (e) {
142
+ const hint = e instanceof Error && 'hint' in e
143
+ ? String(e.hint)
144
+ : 'Pass a decimal string or a Decimal.';
145
+ return fail(model, [key], `field '${key}' expects an exact decimal.`, hint);
146
+ }
147
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Writes (RFC 0004 §7.6): `create()` inserts immediately, `write()` goes through the unit of work and is flushed in
3
+ * set-based statements, `unlink()` deletes immediately. Every change is journaled for savepoint rollback and
4
+ * recorded as a compute trigger (RFC 0008 §7.2).
5
+ */
6
+ import type { ScopeInternals } from '../env/env.js';
7
+ import type { AnyModel } from '../model/model.js';
8
+ /** What the write runtime needs from the recordset runtime (passed in to avoid a module cycle). */
9
+ export interface WriteHost {
10
+ readonly internals: ScopeInternals;
11
+ /** Loads the given fields for ids (through the identity map). */
12
+ fetch(model: AnyModel, ids: readonly number[], fields: ReadonlySet<string>): Promise<void>;
13
+ /** Loads currencies / units referenced by the given fields of the records. */
14
+ ensureValueObjects(model: AnyModel, ids: readonly number[], fields: ReadonlySet<string>): Promise<void>;
15
+ /** Default (stored, non-x2many) keys of a model, with sibling currency / uom fields. */
16
+ defaults(model: AnyModel): Set<string>;
17
+ /** Cached values of a record, created when `create` is true. */
18
+ values(model: string, id: number, create?: boolean): Map<string, unknown> | undefined;
19
+ /** Children of an x2many relation, loading them if needed. */
20
+ children(model: AnyModel, id: number, key: string): Promise<number[]>;
21
+ /** A recordset of `ids` (for inverse functions). */
22
+ recordset(model: AnyModel, ids: readonly number[]): unknown;
23
+ }
24
+ type Row = Readonly<Record<string, unknown>>;
25
+ /** Inserts `rows` and returns their ids in input order. Children and links are created too. */
26
+ export declare function createRecords(host: WriteHost, model: AnyModel, rows: readonly Row[], options?: {
27
+ readonly copy?: boolean;
28
+ }): Promise<number[]>;
29
+ /** One value in COPY text format: \N for null, backslash escapes, bytea as hex (RFC 0015 §7.1). */
30
+ export declare function copyField(value: unknown): string;
31
+ /** Applies `values` to `ids` in the cache and marks them dirty; x2many commands run immediately. */
32
+ export declare function writeRecords(host: WriteHost, model: AnyModel, ids: readonly number[], values: Row): Promise<void>;
33
+ /** Deletes `ids` now and removes them from the cache (and from any cached x2many lists). */
34
+ export declare function unlinkRecords(host: WriteHost, model: AnyModel, ids: readonly number[]): Promise<void>;
35
+ /** Writes dirty records of `modelName` (or all models) in one `UPDATE … FROM unnest(...)` per (model, field set). */
36
+ export declare function flushDirty(host: WriteHost, modelName?: string): Promise<void>;
37
+ export {};