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,52 @@
1
+ /**
2
+ * The dependency graph of computed fields (RFC 0008 §7.1): every `depends` path becomes triggers that say which
3
+ * computed field a change reaches and how to walk back to its records; computed fields get a rank so chains compute
4
+ * in order.
5
+ */
6
+ import type { Field } from '../model/field.js';
7
+ import { type AnyModel, type ResolvedConstraint } from '../model/model.js';
8
+ /** One step of a depends path: field `key` of `model`, leading to `target` for relations. */
9
+ export interface PathStep {
10
+ readonly model: string;
11
+ readonly key: string;
12
+ readonly kind: Field['kind'];
13
+ readonly target: string | undefined;
14
+ /** For one2many: the many2one on the target pointing back. */
15
+ readonly inverse: string | undefined;
16
+ }
17
+ /** A computed field and its parsed dependencies. */
18
+ export interface ComputedField {
19
+ readonly model: string;
20
+ readonly key: string;
21
+ readonly stored: boolean;
22
+ /** Identity of the compute: the function, or the method name. One compute may fill several fields. */
23
+ readonly compute: string | ((records: never) => unknown);
24
+ readonly paths: readonly (readonly PathStep[])[];
25
+ /** Dependency depth: 0 when no path touches a computed field. */
26
+ readonly rank: number;
27
+ }
28
+ /** How a change of `(model, key)` reaches a computed field: walk `reverse` from the changed records, last step first. */
29
+ export interface Trigger {
30
+ readonly field: ComputedField;
31
+ /** The steps from the computed field's model down to the changed model (empty when they are the same). */
32
+ readonly reverse: readonly PathStep[];
33
+ }
34
+ /** The built graph (RFC 0008 §9). */
35
+ export interface ComputeGraph {
36
+ readonly fields: readonly ComputedField[];
37
+ /** model → key → the computed fields a change of that key reaches. */
38
+ readonly triggers: ReadonlyMap<string, ReadonlyMap<string, readonly Trigger[]>>;
39
+ field(model: string, key: string): ComputedField | undefined;
40
+ /** Stored computed fields of a model. */
41
+ stored(model: string): readonly ComputedField[];
42
+ /** many2one keys of `model` that are inverses of one2many steps in some path: changing or deleting them moves records between parents. */
43
+ inverseKeys(model: string): ReadonlySet<string>;
44
+ /** Business constraints of `model` that a change of `key` triggers (RFC 0009 §7.1). */
45
+ constraints(model: string, key: string): readonly ResolvedConstraint[];
46
+ }
47
+ type Models = ReadonlyMap<string, {
48
+ readonly model: AnyModel;
49
+ }>;
50
+ /** Builds the graph for the registry's models. @throws {ComputeCycleError} */
51
+ export declare function buildComputeGraph(models: Models): ComputeGraph;
52
+ export {};
@@ -0,0 +1,162 @@
1
+ /**
2
+ * The dependency graph of computed fields (RFC 0008 §7.1): every `depends` path becomes triggers that say which
3
+ * computed field a change reaches and how to walk back to its records; computed fields get a rank so chains compute
4
+ * in order.
5
+ */
6
+ import { ComputeCycleError, InvalidDependsPathError } from '../errors.js';
7
+ import { defaultDisplayName } from '../model/model.js';
8
+ function targetOf(field) {
9
+ return field.target;
10
+ }
11
+ function parsePath(models, model, path) {
12
+ const steps = [];
13
+ let current = model;
14
+ for (const key of path.split('.')) {
15
+ const f = current.fields[key];
16
+ if (f === undefined)
17
+ throw new Error(`Unchecked depends path '${path}' on ${model.name}.`); // the registry validated paths
18
+ const target = targetOf(f);
19
+ steps.push({
20
+ model: current.name,
21
+ key,
22
+ kind: f.kind,
23
+ target,
24
+ inverse: f.kind === 'one2many' ? f.inverseField : undefined,
25
+ });
26
+ if (target !== undefined) {
27
+ const next = models.get(target);
28
+ if (next === undefined)
29
+ throw new Error(`Unchecked target '${target}' in '${path}'.`);
30
+ current = next.model;
31
+ }
32
+ }
33
+ return steps;
34
+ }
35
+ /** Builds the graph for the registry's models. @throws {ComputeCycleError} */
36
+ export function buildComputeGraph(models) {
37
+ const fields = [];
38
+ const byName = new Map();
39
+ const pending = [];
40
+ for (const { model } of models.values()) {
41
+ for (const [key, field] of Object.entries(model.fields)) {
42
+ if (!field.computed || field.compute === undefined)
43
+ continue;
44
+ const paths = field.compute === defaultDisplayName
45
+ ? [model.recName]
46
+ : field.depends;
47
+ const parsed = paths.map((p) => parsePath(models, model, p));
48
+ const deps = new Set();
49
+ for (const steps of parsed) {
50
+ for (const step of steps) {
51
+ const stepField = models.get(step.model)?.model.fields[step.key];
52
+ if (stepField?.computed)
53
+ deps.add(`${step.model}.${step.key}`);
54
+ }
55
+ }
56
+ pending.push({
57
+ field: {
58
+ model: model.name,
59
+ key,
60
+ stored: field.store,
61
+ compute: field.compute,
62
+ paths: parsed,
63
+ },
64
+ deps,
65
+ });
66
+ }
67
+ }
68
+ // Ranks by depth-first search with cycle detection.
69
+ const ranks = new Map();
70
+ const visiting = [];
71
+ const byKey = new Map(pending.map((p) => [`${p.field.model}.${p.field.key}`, p]));
72
+ const rankOf = (name) => {
73
+ const known = ranks.get(name);
74
+ if (known !== undefined)
75
+ return known;
76
+ const entry = byKey.get(name);
77
+ if (entry === undefined)
78
+ return 0;
79
+ const at = visiting.indexOf(name);
80
+ if (at >= 0)
81
+ throw new ComputeCycleError([...visiting.slice(at), name]);
82
+ visiting.push(name);
83
+ let rank = 0;
84
+ for (const dep of entry.deps)
85
+ rank = Math.max(rank, rankOf(dep) + 1);
86
+ visiting.pop();
87
+ ranks.set(name, rank);
88
+ return rank;
89
+ };
90
+ for (const p of pending) {
91
+ const name = `${p.field.model}.${p.field.key}`;
92
+ const built = { ...p.field, rank: rankOf(name) };
93
+ fields.push(built);
94
+ byName.set(name, built);
95
+ }
96
+ const triggers = new Map();
97
+ const inverses = new Map();
98
+ const add = (model, key, trigger) => {
99
+ let byField = triggers.get(model);
100
+ if (byField === undefined) {
101
+ byField = new Map();
102
+ triggers.set(model, byField);
103
+ }
104
+ let list = byField.get(key);
105
+ if (list === undefined) {
106
+ list = [];
107
+ byField.set(key, list);
108
+ }
109
+ list.push(trigger);
110
+ };
111
+ for (const field of fields) {
112
+ for (const steps of field.paths) {
113
+ steps.forEach((step, i) => {
114
+ add(step.model, step.key, { field, reverse: steps.slice(0, i) });
115
+ if (step.kind === 'one2many' && step.target !== undefined && step.inverse !== undefined) {
116
+ let set = inverses.get(step.target);
117
+ if (set === undefined) {
118
+ set = new Set();
119
+ inverses.set(step.target, set);
120
+ }
121
+ set.add(step.inverse);
122
+ }
123
+ });
124
+ }
125
+ }
126
+ // Constraints: depends are same-model field keys (RFC 0009 §7.1).
127
+ const constraintIndex = new Map();
128
+ for (const { model } of models.values()) {
129
+ for (const c of model.constraints) {
130
+ for (const dep of c.depends) {
131
+ if (dep.includes('.') || model.fields[dep] === undefined) {
132
+ throw new InvalidDependsPathError(`The depends '${dep}' of constraint '${c.key}' on '${model.name}' is not a field of the model.`, 'Constraint depends are field keys of the model itself (no dotted paths); put the rule on the model that owns the data, or depend on a computed field.');
133
+ }
134
+ let byKey = constraintIndex.get(model.name);
135
+ if (byKey === undefined) {
136
+ byKey = new Map();
137
+ constraintIndex.set(model.name, byKey);
138
+ }
139
+ byKey.set(dep, [...(byKey.get(dep) ?? []), c]);
140
+ }
141
+ }
142
+ }
143
+ const noConstraints = Object.freeze([]);
144
+ const none = Object.freeze([]);
145
+ const empty = new Set();
146
+ const storedByModel = new Map();
147
+ for (const f of fields) {
148
+ if (!f.stored)
149
+ continue;
150
+ const list = storedByModel.get(f.model) ?? [];
151
+ list.push(f);
152
+ storedByModel.set(f.model, list);
153
+ }
154
+ return {
155
+ fields: Object.freeze(fields),
156
+ triggers,
157
+ field: (model, key) => byName.get(`${model}.${key}`),
158
+ stored: (model) => storedByModel.get(model) ?? none,
159
+ inverseKeys: (model) => inverses.get(model) ?? empty,
160
+ constraints: (model, key) => constraintIndex.get(model)?.get(key) ?? noConstraints,
161
+ };
162
+ }
@@ -0,0 +1,59 @@
1
+ import type { Id } from '../model/id.js';
2
+ import type { AnyModel } from '../model/model.js';
3
+ declare const REF: unique symbol;
4
+ /** One record a module ships: created (`record`) or a dependency's record updated (`override`). */
5
+ export interface DataRecord {
6
+ readonly kind: 'record' | 'override';
7
+ readonly model: string;
8
+ /** Local name for `record` (`'currency_bdt'`), full external id for `override` (`'base.main_company'`). */
9
+ readonly name: string;
10
+ readonly values: Readonly<Record<string, unknown>>;
11
+ /** Created once, then owned by the users: never updated or deleted by later loads. */
12
+ readonly noupdate: boolean;
13
+ }
14
+ /** A reference to a data record, resolved to its id at load time. */
15
+ export interface DataRef {
16
+ readonly [REF]: true;
17
+ readonly model: string;
18
+ readonly id: string;
19
+ }
20
+ /** True for a value made by {@link ref}. */
21
+ export declare function isRef(value: unknown): value is DataRef;
22
+ /**
23
+ * A record the module ships, with external id `<module>.<name>`.
24
+ * @example record('res.currency', 'currency_bdt', { name: 'BDT', rounding: '0.01' })
25
+ */
26
+ export declare function record(model: string, name: string, values: Readonly<Record<string, unknown>>, options?: {
27
+ readonly noupdate?: boolean;
28
+ }): DataRecord;
29
+ /**
30
+ * Updates a record a dependency ships (`'base.main_company'`): same model, update only.
31
+ * @example override('res.company', 'base.main_company', { name: 'Acme Ltd' })
32
+ */
33
+ export declare function override(model: string, id: string, values: Readonly<Record<string, unknown>>): DataRecord;
34
+ /**
35
+ * A reference to a data record of `model`, usable wherever an id of `model` is (many2one values, x2many `link` /
36
+ * `set`). Checked when the registry is built; resolved when data is loaded.
37
+ */
38
+ export declare function ref<M extends string>(model: M, id: string): Id<M>;
39
+ /** The full external id of a record of `module`. */
40
+ export declare function fullId(module: string, record: DataRecord): string;
41
+ /** Every reference inside a value (nested commands and arrays included). */
42
+ export declare function refsIn(value: unknown, out?: DataRef[]): DataRef[];
43
+ interface DataModule {
44
+ readonly name: string;
45
+ readonly depends: readonly DataModule[];
46
+ readonly data: readonly DataRecord[];
47
+ }
48
+ /**
49
+ * Checks the data of every module, in load order (RFC 0017 §4): record names, duplicates, override targets, field
50
+ * names, and that every reference names a record of the given model declared earlier in the module or in a
51
+ * dependency. Returns external id → model. @throws {InvalidModuleError}
52
+ */
53
+ export declare function validateData(modules: readonly DataModule[], models: ReadonlyMap<string, {
54
+ readonly model: AnyModel;
55
+ }>): ReadonlyMap<string, {
56
+ readonly module: string;
57
+ readonly model: string;
58
+ }>;
59
+ export {};
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Module data (RFC 0017): records a module ships, identified by external ids (`module.name`), and references between
3
+ * them. Declarations are plain values; {@link validateData} checks every name and reference when the registry is
4
+ * built, so broken data never reaches a database.
5
+ */
6
+ import { InvalidModuleError } from '../errors.js';
7
+ const REF = Symbol.for('shutro.ref');
8
+ const LOCAL = /^[a-z][a-z0-9_]*$/;
9
+ const FULL = /^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/;
10
+ /** True for a value made by {@link ref}. */
11
+ export function isRef(value) {
12
+ return (typeof value === 'object' && value !== null && value[REF] === true);
13
+ }
14
+ /**
15
+ * A record the module ships, with external id `<module>.<name>`.
16
+ * @example record('res.currency', 'currency_bdt', { name: 'BDT', rounding: '0.01' })
17
+ */
18
+ export function record(model, name, values, options = {}) {
19
+ if (!LOCAL.test(name))
20
+ throw new InvalidModuleError(`${JSON.stringify(name)} is not a data record name.`, "Use a local snake_case name such as 'currency_bdt'; the module name is added (base.currency_bdt).");
21
+ return Object.freeze({
22
+ kind: 'record',
23
+ model,
24
+ name,
25
+ values,
26
+ noupdate: options.noupdate === true,
27
+ });
28
+ }
29
+ /**
30
+ * Updates a record a dependency ships (`'base.main_company'`): same model, update only.
31
+ * @example override('res.company', 'base.main_company', { name: 'Acme Ltd' })
32
+ */
33
+ export function override(model, id, values) {
34
+ if (!FULL.test(id))
35
+ throw new InvalidModuleError(`${JSON.stringify(id)} is not an external id.`, "Override a dependency's record by its full id, e.g. 'base.main_company'.");
36
+ return Object.freeze({ kind: 'override', model, name: id, values, noupdate: false });
37
+ }
38
+ /**
39
+ * A reference to a data record of `model`, usable wherever an id of `model` is (many2one values, x2many `link` /
40
+ * `set`). Checked when the registry is built; resolved when data is loaded.
41
+ */
42
+ export function ref(model, id) {
43
+ if (!FULL.test(id))
44
+ throw new InvalidModuleError(`${JSON.stringify(id)} is not an external id.`, "Refer to records by their full id, e.g. ref('res.currency', 'base.currency_bdt').");
45
+ return Object.freeze({ [REF]: true, model, id });
46
+ }
47
+ /** The full external id of a record of `module`. */
48
+ export function fullId(module, record) {
49
+ return record.kind === 'override' ? record.name : `${module}.${record.name}`;
50
+ }
51
+ /** Every reference inside a value (nested commands and arrays included). */
52
+ export function refsIn(value, out = []) {
53
+ if (isRef(value))
54
+ out.push(value);
55
+ else if (Array.isArray(value))
56
+ for (const v of value)
57
+ refsIn(v, out);
58
+ else if (typeof value === 'object' &&
59
+ value !== null &&
60
+ Object.getPrototypeOf(value) === Object.prototype)
61
+ for (const v of Object.values(value))
62
+ refsIn(v, out);
63
+ return out;
64
+ }
65
+ function closure(module, out = new Set()) {
66
+ for (const d of module.depends) {
67
+ if (out.has(d.name))
68
+ continue;
69
+ out.add(d.name);
70
+ closure(d, out);
71
+ }
72
+ return out;
73
+ }
74
+ /**
75
+ * Checks the data of every module, in load order (RFC 0017 §4): record names, duplicates, override targets, field
76
+ * names, and that every reference names a record of the given model declared earlier in the module or in a
77
+ * dependency. Returns external id → model. @throws {InvalidModuleError}
78
+ */
79
+ export function validateData(modules, models) {
80
+ const index = new Map();
81
+ for (const module of modules) {
82
+ const deps = closure(module);
83
+ const visible = (id) => {
84
+ const found = index.get(id);
85
+ return found !== undefined && (found.module === module.name || deps.has(found.module))
86
+ ? found
87
+ : undefined;
88
+ };
89
+ for (const rec of module.data) {
90
+ const id = fullId(module.name, rec);
91
+ const where = `Data record '${id}' of module '${module.name}'`;
92
+ const target = models.get(rec.model)?.model;
93
+ if (target === undefined)
94
+ throw new InvalidModuleError(`${where} is of model '${rec.model}', which is not installed.`, 'Fix the model name, or depend on the module that defines it.');
95
+ for (const key of Object.keys(rec.values))
96
+ if (target.fields[key] === undefined)
97
+ throw new InvalidModuleError(`${where} sets '${key}', which is not a field of ${rec.model}.`, `Fields: ${Object.keys(target.fields).join(', ')}.`);
98
+ for (const r of refsIn(rec.values)) {
99
+ const found = visible(r.id);
100
+ if (found === undefined)
101
+ throw new InvalidModuleError(`${where} refers to '${r.id}', which is not declared before it in this module or in a dependency.`, 'Declare the referenced record first (data loads in order), or add the module that ships it to depends.');
102
+ if (found.model !== r.model)
103
+ throw new InvalidModuleError(`${where} refers to '${r.id}' as ${r.model}, but it is a ${found.model}.`, 'Fix the model in ref().');
104
+ }
105
+ if (rec.kind === 'override') {
106
+ const owner = index.get(id);
107
+ if (owner === undefined || !deps.has(owner.module))
108
+ throw new InvalidModuleError(`${where} overrides '${id}', which no dependency declares.`, 'Override records of modules this one depends on.');
109
+ if (owner.model !== rec.model)
110
+ throw new InvalidModuleError(`${where} overrides '${id}' as ${rec.model}, but it is a ${owner.model}.`, "Use the record's model.");
111
+ continue;
112
+ }
113
+ if (index.has(id))
114
+ throw new InvalidModuleError(`${where} is declared twice.`, 'External ids are unique: rename one of them.');
115
+ index.set(id, { module: module.name, model: rec.model });
116
+ }
117
+ }
118
+ return index;
119
+ }
@@ -0,0 +1,37 @@
1
+ import { type Env, type ScopeInternals, type Shutro } from '../env/env.js';
2
+ import type { Id } from '../model/id.js';
3
+ /** The external-id table (RFC 0017 §4). */
4
+ export declare const EXTERNAL_ID_TABLE = "shutro_external_id";
5
+ /** Statements that create the external-id table (for migrations or tests). */
6
+ export declare function externalIdTableStatements(): readonly {
7
+ readonly text: string;
8
+ readonly params: readonly [];
9
+ }[];
10
+ /** The record id of external id `id` (cached per transaction). @throws {UnknownExternalIdError} */
11
+ export declare function resolveExternalId(internals: ScopeInternals, id: string, model?: string): Promise<number>;
12
+ /** `env.refId(model, id)`. */
13
+ export declare function refId<M extends string>(env: Env, model: M, id: string): Promise<Id<M>>;
14
+ /** What {@link loadData} did for one module. */
15
+ export interface DataLoadResult {
16
+ readonly module: string;
17
+ readonly created: readonly string[];
18
+ readonly updated: readonly string[];
19
+ readonly unchanged: number;
20
+ /** `noupdate` records that already exist: left to the users. */
21
+ readonly kept: readonly string[];
22
+ readonly deleted: readonly string[];
23
+ /** Ids no longer declared whose record could not be deleted (still referenced): kept, with the reason. */
24
+ readonly retained: readonly {
25
+ readonly id: string;
26
+ readonly reason: string;
27
+ }[];
28
+ }
29
+ /**
30
+ * Loads the data of every installed module (RFC 0017 §4), idempotently: new ids are created, changed records
31
+ * updated, unchanged ones skipped (checksums), `noupdate` records left alone once they exist, and ids no longer
32
+ * declared deleted with their records. Run by `shutro migrate apply` after the schema.
33
+ */
34
+ export declare function loadData(shutro: Shutro, options?: {
35
+ readonly company?: number;
36
+ readonly modules?: readonly string[];
37
+ }): Promise<DataLoadResult[]>;
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Loading module data and resolving external ids (RFC 0017 §4). Each module's data loads in one system transaction
3
+ * (`shutro.bootstrap`), in module load order, through the ORM: computes, sequences, constraints and the audit trail
4
+ * apply as for any create or write.
5
+ */
6
+ import { createHash } from 'node:crypto';
7
+ import { compile, sql } from '../../sql/index.js';
8
+ import { Decimal as DecimalJs } from 'decimal.js';
9
+ import { internalsOf } from '../env/env.js';
10
+ import { UnknownExternalIdError } from '../errors.js';
11
+ import { fullId, isRef } from './data.js';
12
+ /** The external-id table (RFC 0017 §4). */
13
+ export const EXTERNAL_ID_TABLE = 'shutro_external_id';
14
+ const DDL = [
15
+ `CREATE TABLE IF NOT EXISTS "${EXTERNAL_ID_TABLE}" ("module" text NOT NULL, "name" text NOT NULL, "model" text NOT NULL, "res_id" bigint NOT NULL, "noupdate" boolean NOT NULL DEFAULT false, "checksum" text, "updated_at" timestamp with time zone NOT NULL DEFAULT now(), PRIMARY KEY ("module", "name"))`,
16
+ `CREATE INDEX IF NOT EXISTS "${EXTERNAL_ID_TABLE}_model_res_id_idx" ON "${EXTERNAL_ID_TABLE}" ("model", "res_id")`,
17
+ ];
18
+ /** Statements that create the external-id table (for migrations or tests). */
19
+ export function externalIdTableStatements() {
20
+ return DDL.map((text) => ({ text, params: [] }));
21
+ }
22
+ async function tableExists(internals) {
23
+ const [row] = await internals.query(compile(sql `SELECT to_regclass(${EXTERNAL_ID_TABLE}) IS NOT NULL AS present`));
24
+ return row?.present === true;
25
+ }
26
+ const lookups = new WeakMap();
27
+ function split(id) {
28
+ const dot = id.indexOf('.');
29
+ return [id.slice(0, dot), id.slice(dot + 1)];
30
+ }
31
+ /** The record id of external id `id` (cached per transaction). @throws {UnknownExternalIdError} */
32
+ export async function resolveExternalId(internals, id, model) {
33
+ let cache = lookups.get(internals.cache);
34
+ if (cache === undefined) {
35
+ cache = new Map();
36
+ lookups.set(internals.cache, cache);
37
+ }
38
+ let found = cache.get(id);
39
+ if (found === undefined) {
40
+ const [module, name] = split(id);
41
+ const rows = name === '' || !(await tableExists(internals))
42
+ ? []
43
+ : await internals.query(compile(sql `SELECT model, res_id FROM ${sql.id(EXTERNAL_ID_TABLE)} WHERE module = ${module} AND name = ${name}`));
44
+ const row = rows[0];
45
+ if (row === undefined)
46
+ throw new UnknownExternalIdError(`The external id '${id}' does not exist.`, 'Check the spelling, and that the module shipping it is installed and its data loaded (shutro migrate apply).');
47
+ found = { model: row.model, id: Number(row.res_id) };
48
+ cache.set(id, found);
49
+ }
50
+ if (model !== undefined && found.model !== model)
51
+ throw new UnknownExternalIdError(`The external id '${id}' is a ${found.model}, not a ${model}.`, 'Use the model of the record.');
52
+ return found.id;
53
+ }
54
+ /** `env.refId(model, id)`. */
55
+ export async function refId(env, model, id) {
56
+ return (await resolveExternalId(internalsOf(env), id, model));
57
+ }
58
+ /** A stable text of declared values for checksums: refs by id, Decimals as strings, sorted keys. */
59
+ function stable(value) {
60
+ if (isRef(value))
61
+ return { $ref: value.id };
62
+ if (DecimalJs.isDecimal(value))
63
+ return { $decimal: value.toString() };
64
+ if (value instanceof Date)
65
+ return { $date: value.toISOString() };
66
+ if (Array.isArray(value))
67
+ return value.map(stable);
68
+ if (typeof value === 'object' && value !== null)
69
+ return Object.fromEntries(Object.keys(value)
70
+ .sort()
71
+ .map((k) => [k, stable(value[k])]));
72
+ return value;
73
+ }
74
+ function checksumOf(record) {
75
+ return createHash('sha256')
76
+ .update(JSON.stringify(stable(record.values)))
77
+ .digest('hex')
78
+ .slice(0, 32);
79
+ }
80
+ async function resolveValues(internals, value) {
81
+ if (isRef(value))
82
+ return resolveExternalId(internals, value.id, value.model);
83
+ if (Array.isArray(value))
84
+ return Promise.all(value.map((v) => resolveValues(internals, v)));
85
+ if (typeof value === 'object' &&
86
+ value !== null &&
87
+ Object.getPrototypeOf(value) === Object.prototype) {
88
+ const out = {};
89
+ for (const [k, v] of Object.entries(value))
90
+ out[k] = await resolveValues(internals, v);
91
+ return out;
92
+ }
93
+ return value;
94
+ }
95
+ /** Values for an update: x2many `create` commands are left out (they would add children at every load). */
96
+ function forUpdate(values) {
97
+ const out = {};
98
+ for (const [k, v] of Object.entries(values)) {
99
+ if (typeof v === 'object' && v !== null && !Array.isArray(v) && 'create' in v) {
100
+ const { create: _create, ...rest } = v;
101
+ if (Object.keys(rest).length > 0)
102
+ out[k] = rest;
103
+ continue;
104
+ }
105
+ out[k] = v;
106
+ }
107
+ return out;
108
+ }
109
+ /**
110
+ * Loads the data of every installed module (RFC 0017 §4), idempotently: new ids are created, changed records
111
+ * updated, unchanged ones skipped (checksums), `noupdate` records left alone once they exist, and ids no longer
112
+ * declared deleted with their records. Run by `shutro migrate apply` after the schema.
113
+ */
114
+ export async function loadData(shutro, options = {}) {
115
+ const results = [];
116
+ const registry = shutro.registry;
117
+ if (registry === undefined)
118
+ throw new UnknownExternalIdError('loadData() needs a Shutro instance with a registry.', 'Pass registry to createShutro.');
119
+ for (const module of registry.modules) {
120
+ if (options.modules !== undefined && !options.modules.includes(module.name))
121
+ continue;
122
+ // Modules without data still run: ids a previous version declared are deleted.
123
+ const result = await shutro.bootstrap({
124
+ reason: `data: ${module.name}`,
125
+ ...(options.company === undefined ? {} : { company: options.company }),
126
+ }, async (env) => loadModule(env, module.name, module.data));
127
+ if (result.created.length +
128
+ result.updated.length +
129
+ result.deleted.length +
130
+ result.unchanged +
131
+ result.kept.length +
132
+ result.retained.length >
133
+ 0)
134
+ results.push(result);
135
+ }
136
+ return results;
137
+ }
138
+ async function loadModule(scoped, module, data) {
139
+ const internals = internalsOf(scoped);
140
+ // Model names come from the data at runtime: an environment untyped over them.
141
+ const env = scoped;
142
+ for (const statement of DDL)
143
+ await internals.query({ text: statement, params: [] });
144
+ const rows = await internals.query(compile(sql `SELECT module, name, model, res_id, noupdate, checksum FROM ${sql.id(EXTERNAL_ID_TABLE)} WHERE module = ${module}`));
145
+ const existing = new Map(rows.map((r) => [r.name, r]));
146
+ const out = {
147
+ module,
148
+ created: [],
149
+ updated: [],
150
+ unchanged: 0,
151
+ kept: [],
152
+ deleted: [],
153
+ retained: [],
154
+ };
155
+ const declared = new Set();
156
+ for (const rec of data) {
157
+ const id = fullId(module, rec);
158
+ const key = rec.kind === 'override' ? id : rec.name; // overrides are bookkept under the overriding module
159
+ declared.add(key);
160
+ const row = existing.get(key);
161
+ const checksum = checksumOf(rec);
162
+ const model = internals.registry.get(rec.model).model;
163
+ const target = rec.kind === 'override'
164
+ ? await resolveExternalId(internals, id, rec.model)
165
+ : row === undefined
166
+ ? undefined
167
+ : Number(row.res_id);
168
+ const alive = target !== undefined &&
169
+ (await internals.query(compile(sql `SELECT ${sql.id('id')} FROM ${sql.id(model.table)} WHERE ${sql.id('id')} = ${target}`))).length > 0;
170
+ // A noupdate record belongs to the users once created: kept as they left it, even deleted.
171
+ if (rec.noupdate && row !== undefined) {
172
+ out.kept.push(id);
173
+ continue;
174
+ }
175
+ const values = (await resolveValues(internals, rec.values));
176
+ if (rec.kind === 'record' && !alive) {
177
+ const created = await env.model(rec.model).create([values]);
178
+ const resId = created.ids[0];
179
+ await internals.query(compile(sql `INSERT INTO ${sql.id(EXTERNAL_ID_TABLE)} (module, name, model, res_id, noupdate, checksum) VALUES (${module}, ${rec.name}, ${rec.model}, ${resId}, ${rec.noupdate}, ${checksum})
180
+ ON CONFLICT (module, name) DO UPDATE SET res_id = EXCLUDED.res_id, model = EXCLUDED.model, noupdate = EXCLUDED.noupdate, checksum = EXCLUDED.checksum, updated_at = now()`));
181
+ lookups.get(internals.cache)?.set(id, { model: rec.model, id: resId });
182
+ out.created.push(id);
183
+ continue;
184
+ }
185
+ if (rec.kind === 'override' && !alive)
186
+ throw new UnknownExternalIdError(`'${id}' (overridden by ${module}) has no record.`, 'Load the owning module first.');
187
+ if (row?.checksum === checksum) {
188
+ out.unchanged++;
189
+ continue;
190
+ }
191
+ await env
192
+ .model(rec.model)
193
+ .browse([target])
194
+ .write(forUpdate(values));
195
+ await internals.query(compile(sql `INSERT INTO ${sql.id(EXTERNAL_ID_TABLE)} (module, name, model, res_id, noupdate, checksum) VALUES (${module}, ${key}, ${rec.model}, ${target}, ${false}, ${checksum})
196
+ ON CONFLICT (module, name) DO UPDATE SET checksum = EXCLUDED.checksum, updated_at = now()`));
197
+ out.updated.push(id);
198
+ }
199
+ // Ids this module no longer declares: delete their records (overrides only lose their bookkeeping).
200
+ for (const [name, row] of existing) {
201
+ if (declared.has(name))
202
+ continue;
203
+ const id = name.includes('.') ? name : `${module}.${name}`;
204
+ if (row.noupdate)
205
+ continue;
206
+ const forget = compile(sql `DELETE FROM ${sql.id(EXTERNAL_ID_TABLE)} WHERE module = ${module} AND name = ${name}`);
207
+ if (name.includes('.')) {
208
+ await internals.query(forget);
209
+ continue;
210
+ }
211
+ const table = internals.registry.has(row.model)
212
+ ? internals.registry.get(row.model).model.table
213
+ : undefined;
214
+ const present = table !== undefined &&
215
+ (await internals.query(compile(sql `SELECT ${sql.id('id')} FROM ${sql.id(table)} WHERE ${sql.id('id')} = ${Number(row.res_id)}`))).length > 0;
216
+ if (!present) {
217
+ await internals.query(forget); // the record is already gone (or its model uninstalled)
218
+ continue;
219
+ }
220
+ try {
221
+ await env.transaction(async (e) => {
222
+ await e
223
+ .model(row.model)
224
+ .browse([Number(row.res_id)])
225
+ .unlink();
226
+ });
227
+ await internals.query(forget);
228
+ out.deleted.push(id);
229
+ }
230
+ catch (error) {
231
+ out.retained.push({ id, reason: error instanceof Error ? error.message : String(error) });
232
+ }
233
+ }
234
+ await env.flush();
235
+ return out;
236
+ }