shutro 0.1.0 → 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 (74) hide show
  1. package/README.md +12 -2
  2. package/dist/audit/index.d.ts +3 -1
  3. package/dist/audit/index.js +2 -0
  4. package/dist/cli/cli.js +17 -2
  5. package/dist/cli/config.js +2 -0
  6. package/dist/cli/generate/generate.js +2 -0
  7. package/dist/cli/generate/render.js +57 -8
  8. package/dist/cli/init.js +4 -4
  9. package/dist/cli/resolve.d.ts +2 -0
  10. package/dist/cli/resolve.js +28 -0
  11. package/dist/core/data/data.d.ts +59 -0
  12. package/dist/core/data/data.js +119 -0
  13. package/dist/core/data/load.d.ts +37 -0
  14. package/dist/core/data/load.js +236 -0
  15. package/dist/core/env/env.d.ts +175 -2
  16. package/dist/core/env/env.js +304 -19
  17. package/dist/core/env/identity.d.ts +10 -0
  18. package/dist/core/env/identity.js +16 -0
  19. package/dist/core/errors.d.ts +15 -1
  20. package/dist/core/errors.js +21 -0
  21. package/dist/core/events/events.d.ts +44 -0
  22. package/dist/core/events/events.js +58 -0
  23. package/dist/core/events/workers.d.ts +56 -0
  24. package/dist/core/events/workers.js +155 -0
  25. package/dist/core/index.d.ts +17 -9
  26. package/dist/core/index.js +11 -3
  27. package/dist/core/model/field.d.ts +33 -0
  28. package/dist/core/model/field.js +64 -1
  29. package/dist/core/model/generated.d.ts +4 -2
  30. package/dist/core/model/model.d.ts +40 -0
  31. package/dist/core/model/model.js +28 -0
  32. package/dist/core/model/related.d.ts +17 -0
  33. package/dist/core/model/related.js +60 -0
  34. package/dist/core/model/typed.d.ts +107 -0
  35. package/dist/core/model/typed.js +46 -0
  36. package/dist/core/money/fx.d.ts +10 -2
  37. package/dist/core/money/fx.js +17 -2
  38. package/dist/core/recordset/aggregate.d.ts +22 -0
  39. package/dist/core/recordset/aggregate.js +258 -0
  40. package/dist/core/recordset/audit.d.ts +9 -1
  41. package/dist/core/recordset/audit.js +59 -2
  42. package/dist/core/recordset/compute.d.ts +2 -0
  43. package/dist/core/recordset/compute.js +11 -2
  44. package/dist/core/recordset/domain.d.ts +4 -0
  45. package/dist/core/recordset/domain.js +74 -2
  46. package/dist/core/recordset/onchange.js +70 -37
  47. package/dist/core/recordset/recordset.d.ts +10 -1
  48. package/dist/core/recordset/recordset.js +80 -14
  49. package/dist/core/recordset/security.d.ts +15 -1
  50. package/dist/core/recordset/security.js +95 -10
  51. package/dist/core/recordset/source.d.ts +9 -0
  52. package/dist/core/recordset/source.js +19 -0
  53. package/dist/core/recordset/transitions.js +4 -1
  54. package/dist/core/recordset/types.d.ts +131 -12
  55. package/dist/core/recordset/values.d.ts +6 -0
  56. package/dist/core/recordset/values.js +34 -4
  57. package/dist/core/recordset/writes.d.ts +6 -1
  58. package/dist/core/recordset/writes.js +217 -12
  59. package/dist/core/registry/ddl.d.ts +9 -0
  60. package/dist/core/registry/ddl.js +49 -2
  61. package/dist/core/registry/module.d.ts +10 -1
  62. package/dist/core/registry/module.js +2 -0
  63. package/dist/core/registry/registry.d.ts +29 -4
  64. package/dist/core/registry/registry.js +100 -5
  65. package/dist/core/security/runtime.d.ts +102 -0
  66. package/dist/core/security/runtime.js +232 -0
  67. package/dist/driver-pg/driver.d.ts +2 -0
  68. package/dist/driver-pg/driver.js +1 -0
  69. package/dist/migrate/schema.js +40 -2
  70. package/dist/security/index.d.ts +24 -0
  71. package/dist/security/index.js +16 -0
  72. package/dist/sql/tag.d.ts +5 -0
  73. package/dist/sql/tag.js +29 -1
  74. package/package.json +1 -1
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  ERP workloads: type-safe, secure by default, modular, multi-company, multi-currency, audit-ready and fast at scale.
5
5
  It is the data layer of the Kosh ERP framework.
6
6
 
7
- > **Status: alpha (0.x).** The engine is tested end to end against real PostgreSQL (550+ tests, an ERP demo with
7
+ > **Status: alpha (0.x).** The engine is tested end to end against real PostgreSQL (600+ tests, an ERP demo with
8
8
  > partner, product, sale and invoice modules), but the API may still change between minor versions. Known gaps are
9
9
  > tracked in [`docs/feedback.md`](docs/feedback.md).
10
10
 
@@ -27,7 +27,16 @@ Requirements: Node.js ≥ 24, PostgreSQL ≥ 14.
27
27
  - **Translations** in JSONB with language fallback; **sequences**, including gapless ones; append-only **audit trail**.
28
28
  - **Security**: default-deny ACL, record rules compiled to SQL (following relations, e.g. "lines of my orders"),
29
29
  optional PostgreSQL row-level security, field-level security, encrypted fields with keys outside the database,
30
- verified identities.
30
+ verified identities, administrator roles that need no grants, feature permissions, special per-user grants,
31
+ back-date permissions for transactions, and audited elevated methods.
32
+ - **Reports**: `aggregate()` (grouped totals with rules applied, per-currency `Money`), `records.sum()`.
33
+ - **Odoo-ORM parity, typed and checked at startup**: module data with external ids (`record`, `ref`, `env.ref`),
34
+ related fields, delegation (`delegates`), hierarchies (`childOf` / `parentOf`), company-dependent fields, search
35
+ on computed fields, and roles / access / rules editable at runtime.
36
+ - **Beyond Odoo**: compare-and-set writes against lost updates, transactional events (outbox) and PostgreSQL jobs
37
+ with exactly-once database effects, and time travel (`history: true`, `env.asOf(instant)`).
38
+ - **Typed definitions**: `shutro generate` writes per-module bindings, so computes, checks, onchange handlers and
39
+ methods are typed with no casts.
31
40
  - **Migrations**: schema diff against the live catalog, versioned migration files, destructive-change guard.
32
41
  - **Tooling**: `shutro init | migrate | generate | inspect`, dev-mode query inspector with N+1 warnings, COPY bulk
33
42
  loads, partitioned tables, CI benchmarks.
@@ -64,6 +73,7 @@ Entry points: `shutro` (core), `shutro/sql`, `shutro/driver-pg`, `shutro/migrate
64
73
  - Guides: [`docs/guides/`](docs/guides/)
65
74
  - Design documents (RFCs): [`docs/rfcs/`](docs/rfcs/README.md)
66
75
  - A complete example: [`examples/erp-demo`](examples/erp-demo/README.md)
76
+ - How it compares with Odoo's ORM, including where Odoo is ahead: [`docs/odoo-comparison.md`](docs/odoo-comparison.md)
67
77
 
68
78
  ## Development
69
79
 
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import { type CompiledSql } from '../sql/index.js';
7
7
  /** What happened. `su` rows record a superuser scope (RFC 0003 §7.6). */
8
- export type AuditAction = 'create' | 'write' | 'unlink' | 'su';
8
+ export type AuditAction = 'create' | 'write' | 'unlink' | 'su' | 'elevate' | 'security';
9
9
  /** One row of the trail. */
10
10
  export interface AuditEntry {
11
11
  readonly id: number;
@@ -44,6 +44,8 @@ export interface TrailFilter {
44
44
  readonly action?: AuditAction | undefined;
45
45
  /** Rows at or after this time. */
46
46
  readonly since?: Date | undefined;
47
+ /** Rows older than this row id: the cursor of the next page (the `id` of the last row of the previous one). */
48
+ readonly before?: number | undefined;
47
49
  /** Newest first; default 100. */
48
50
  readonly limit?: number | undefined;
49
51
  }
@@ -70,6 +70,8 @@ export function trailQuery(filter = {}) {
70
70
  conditions.push(sql `${sql.id('action')} = ${filter.action}`);
71
71
  if (filter.since !== undefined)
72
72
  conditions.push(sql `${sql.id('at')} >= ${filter.since}`);
73
+ if (filter.before !== undefined)
74
+ conditions.push(sql `${sql.id('id')} < ${filter.before}`);
73
75
  const where = conditions.length === 0 ? sql.empty : sql ` WHERE ${sql.join(conditions, sql ` AND `)}`;
74
76
  return compile(sql `SELECT ${sql.id('id')}, ${sql.id('at')}, ${sql.id('tx')}, ${sql.id('uid')}, ${sql.id('company_id')}, ${sql.id('su')}, ${sql.id('reason')}, ${sql.id('action')}, ${sql.id('model')}, ${sql.id('record_id')}, ${sql.id('field')}, ${sql.id('old')}, ${sql.id('new')} FROM ${sql.id(AUDIT_TABLE)}${where} ORDER BY ${sql.id('id')} DESC LIMIT ${filter.limit ?? 100}`);
75
77
  }
package/dist/cli/cli.js CHANGED
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { resolve } from 'node:path';
6
6
  import { parseArgs } from 'node:util';
7
+ import { createShutro, historyStatements, loadData } from '../core/index.js';
7
8
  import { applyMigrations, migrationStatus, planMigration, writeMigrationFile, } from '../migrate/index.js';
8
9
  import { loadConfig } from './config.js';
9
10
  import { CliError } from './errors.js';
@@ -19,7 +20,7 @@ Commands:
19
20
  migrate status Applied and pending migration files
20
21
  migrate plan What the database is missing (DDL, destructive statements marked)
21
22
  migrate write <name> Write the plan as the next migration file
22
- migrate apply [--allow-destructive] Apply pending files, then module data-migration hooks
23
+ migrate apply [--allow-destructive] Apply pending files, data-migration hooks, then module data
23
24
  inspect [model] Modules and models, or one model: fields, origins, methods, computes,
24
25
  constraints, access and rules
25
26
 
@@ -138,7 +139,21 @@ async function migrate(sub, name, configFile, allowDestructive, io, env) {
138
139
  io.write(`module ${m.module} ${m.from ?? '(new)'} → ${m.to}\n`);
139
140
  for (const h of result.hooks)
140
141
  io.write(`hook ${h.module} ${h.version}\n`);
141
- if (result.applied.length + result.modules.length === 0)
142
+ // History triggers (RFC 0018 §7.4): idempotent, after the schema they version.
143
+ for (const statement of historyStatements(registry))
144
+ await driver.query(statement);
145
+ // Module data (RFC 0017), after the schema: idempotent, so it runs at every apply.
146
+ const data = await loadData(createShutro({ driver, registry }));
147
+ let dataChanges = 0;
148
+ for (const d of data) {
149
+ const changes = d.created.length + d.updated.length + d.deleted.length;
150
+ dataChanges += changes;
151
+ if (changes > 0)
152
+ io.write(`data ${d.module}: ${d.created.length} created, ${d.updated.length} updated, ${d.deleted.length} deleted, ${d.unchanged} unchanged\n`);
153
+ for (const r of d.retained)
154
+ io.write(`kept ${r.id} (still referenced: ${r.reason})\n`);
155
+ }
156
+ if (result.applied.length + result.modules.length + dataChanges === 0)
142
157
  io.write('Up to date.\n');
143
158
  return 0;
144
159
  }
@@ -5,6 +5,7 @@ import { existsSync } from 'node:fs';
5
5
  import { isAbsolute, resolve } from 'node:path';
6
6
  import { pathToFileURL } from 'node:url';
7
7
  import { ConfigError } from './errors.js';
8
+ import { allowJsSpecifiersForTs } from './resolve.js';
8
9
  /** Identity helper that types the config file. */
9
10
  export function defineConfig(config) {
10
11
  return config;
@@ -27,6 +28,7 @@ export async function loadConfig(file) {
27
28
  if (!existsSync(path)) {
28
29
  throw new ConfigError(`Config file ${path} does not exist.`, 'Create shutro.config.ts with `export default defineConfig({ modules: [...] })`, or pass --config.');
29
30
  }
31
+ allowJsSpecifiersForTs();
30
32
  const loaded = (await import(pathToFileURL(path).href));
31
33
  const config = loaded.default ?? loaded.config;
32
34
  if (!isConfig(config)) {
@@ -7,6 +7,7 @@ import { dirname, join, relative } from 'node:path';
7
7
  import { pathToFileURL } from 'node:url';
8
8
  import { buildRegistry, isModule } from '../../core/index.js';
9
9
  import { ConfigError, ModuleSourceError } from '../errors.js';
10
+ import { allowJsSpecifiersForTs } from '../resolve.js';
10
11
  import { outDirOf, renderAppIndex, renderBindings, renderSchema, } from './render.js';
11
12
  /** Imports the module files of a config (one `defineModule` export each). */
12
13
  export async function loadSources(files) {
@@ -15,6 +16,7 @@ export async function loadSources(files) {
15
16
  if (!existsSync(file)) {
16
17
  throw new ConfigError(`Module file ${file} does not exist.`, 'Check `modules` in shutro.config.ts.');
17
18
  }
19
+ allowJsSpecifiersForTs();
18
20
  const ns = (await import(pathToFileURL(file).href));
19
21
  const found = Object.entries(ns).filter(([, value]) => isModule(value));
20
22
  if (found.length !== 1) {
@@ -8,13 +8,36 @@ import { CORE_PACKAGE } from '../packages.js';
8
8
  const HEADER = '// GENERATED by `shutro generate`. Do not edit.';
9
9
  /** Short, stable hash of everything the view depends on (RFC 0002 §7.7 "definitions hash"). */
10
10
  export function definitionsHash(registry) {
11
+ // Only what the generated types depend on (feedback #17): field types, origins and transitions. Labels, help,
12
+ // indexes, security metadata and module versions change no type and must not churn the files.
11
13
  const names = [...registry.models.keys()].sort();
12
- const definitions = {
13
- modules: registry.modules.map((m) => [m.name, m.version]),
14
- models: names.map((name) => registry.describe(name)),
15
- };
14
+ const definitions = names.map((name) => {
15
+ const registered = registry.get(name);
16
+ return {
17
+ name,
18
+ module: registered.module,
19
+ extensions: registered.extensions,
20
+ fields: Object.entries(registered.model.fields).map(([key, field]) => [
21
+ key,
22
+ fieldType(name, key, field),
23
+ registered.fieldOrigins[key] ?? null,
24
+ ]),
25
+ transitions: transitionNames(registered),
26
+ };
27
+ });
16
28
  return createHash('sha256').update(JSON.stringify(definitions)).digest('hex').slice(0, 16);
17
29
  }
30
+ /** Every transition of the model's state fields, extensions' `transitionsAdd` included (feedback #18). */
31
+ function transitionNames(registered) {
32
+ const names = new Set();
33
+ for (const field of Object.values(registered.model.fields)) {
34
+ const transitions = field.transitions;
35
+ if (field.kind === 'state' && transitions !== undefined)
36
+ for (const name of Object.keys(transitions))
37
+ names.add(name);
38
+ }
39
+ return [...names].sort();
40
+ }
18
41
  /** `sale.order.line` → `SaleOrderLine`. */
19
42
  export function interfaceName(model) {
20
43
  return model
@@ -116,16 +139,28 @@ export function importSpecifier(fromDir, file) {
116
139
  const spec = relative(fromDir, file).replace(/\\/g, '/').replace(/\.ts$/, '.js');
117
140
  return spec.startsWith('.') ? spec : `./${spec}`;
118
141
  }
119
- function methodsType(registered, sources, outDir) {
142
+ /**
143
+ * The methods interface of a model: it extends each contributing module's declared methods and lists the
144
+ * transitions (extensions' `transitionsAdd` included). A named interface, because TypeScript resolves interface
145
+ * bases lazily: typed definition callbacks in a module can then name the view without depending on the module's own
146
+ * type (TS7022, feedback #1).
147
+ */
148
+ function methodsInterface(registered, sources, outDir) {
120
149
  const contributors = [registered.module, ...registered.extensions];
121
- const parts = contributors.map((name) => {
150
+ const bases = contributors.map((name) => {
122
151
  const source = sources.get(name);
123
152
  if (source === undefined)
124
153
  throw new Error(`No source for module '${name}'.`);
125
154
  const spec = importSpecifier(outDir, source.file);
126
155
  return `F.Methods<typeof import(${quote(spec)}).${source.exportName}, ${quote(registered.model.name)}>`;
127
156
  });
128
- return parts.join(' & ');
157
+ const name = `${interfaceName(registered.model.name)}Methods`;
158
+ return [
159
+ `/** Methods of \`${registered.model.name}\`: declared ones and transitions. */`,
160
+ `export interface ${name} extends ${bases.join(', ')} {`,
161
+ ...transitionNames(registered).map((t) => ` readonly ${quote(t)}: () => Promise<void>;`),
162
+ '}',
163
+ ];
129
164
  }
130
165
  /** Renders `schema.d.ts` for a registry (a module view or the application view). */
131
166
  export function renderSchema(registry, sources, outDir, title) {
@@ -153,7 +188,8 @@ export function renderSchema(registry, sources, outDir, title) {
153
188
  const comment = from === undefined || from === registered.module ? '' : ` // ${from}`;
154
189
  lines.push(` readonly ${key}: ${fieldType(name, key, field)};${comment}`);
155
190
  }
156
- lines.push(' };', ` readonly methods: ${methodsType(registered, sources, outDir)};`, '}');
191
+ lines.push(' };', ` readonly methods: ${interfaceName(name)}Methods;`, '}');
192
+ lines.push('', ...methodsInterface(registered, sources, outDir));
157
193
  }
158
194
  return `${lines.join('\n')}\n`;
159
195
  }
@@ -177,7 +213,20 @@ export function renderBindings(registry, module) {
177
213
  `${HEADER} definitions-hash: ${definitionsHash(registry)}`,
178
214
  `// Bindings of module \`${module}\`: import the definition API from here to get types scoped to what it can see.`,
179
215
  `export { defineModel, defineModule, extendModel, f, replace } from '${CORE_PACKAGE}';`,
216
+ `import { type DefinitionHelpers, definitions } from '${CORE_PACKAGE}';`,
180
217
  ...ALIASES,
218
+ '',
219
+ "/** Definition callbacks typed against this module's view: no casts in computes, checks, onchange, methods. */",
220
+ 'const helpers: DefinitionHelpers<SchemaView> = definitions<SchemaView>();',
221
+ "export const compute: DefinitionHelpers<SchemaView>['compute'] = helpers.compute;",
222
+ "export const check: DefinitionHelpers<SchemaView>['check'] = helpers.check;",
223
+ "export const onchange: DefinitionHelpers<SchemaView>['onchange'] = helpers.onchange;",
224
+ "export const records: DefinitionHelpers<SchemaView>['records'] = helpers.records;",
225
+ "export const method: DefinitionHelpers<SchemaView>['method'] = helpers.method;",
226
+ "/** Module data (RFC 0017): records, overrides of dependencies' records, and references, typed like creates. */",
227
+ "export const record: DefinitionHelpers<SchemaView>['record'] = helpers.record;",
228
+ "export const override: DefinitionHelpers<SchemaView>['override'] = helpers.override;",
229
+ "export const ref: DefinitionHelpers<SchemaView>['ref'] = helpers.ref;",
181
230
  ].join('\n')}\n`;
182
231
  }
183
232
  /** Renders the application's `index.ts`: `createShutro` typed to the full view. */
package/dist/cli/init.js CHANGED
@@ -18,12 +18,12 @@ export default defineConfig({
18
18
  'modules/base/module.ts': `import { defineGroup, defineModel, defineModule, f } from '${CORE_PACKAGE}';
19
19
 
20
20
  export const ResUsers = defineModel('res.users', {
21
- access: { 'base.user': ['read'], 'base.admin': ['read', 'write', 'create', 'unlink'] },
21
+ access: { 'base.user': ['read'] }, // administrators need no grant
22
22
  fields: { login: f.char({ required: true, index: 'unique' }), name: f.char({ required: true }) },
23
23
  });
24
24
 
25
25
  export const ResCurrency = defineModel('res.currency', {
26
- access: { 'base.user': ['read'], 'base.admin': ['read', 'write', 'create', 'unlink'] },
26
+ access: { 'base.user': ['read'] }, // administrators need no grant
27
27
  fields: {
28
28
  name: f.char({ required: true, size: 3, index: 'unique' }),
29
29
  rounding: f.decimal({ scale: 6, required: true, default: '0.01' }),
@@ -32,7 +32,7 @@ export const ResCurrency = defineModel('res.currency', {
32
32
  });
33
33
 
34
34
  export const ResCompany = defineModel('res.company', {
35
- access: { 'base.user': ['read'], 'base.admin': ['read', 'write', 'create', 'unlink'] },
35
+ access: { 'base.user': ['read'] }, // administrators need no grant
36
36
  fields: { name: f.char({ required: true }), currency: f.many2one('res.currency', { required: true }) },
37
37
  });
38
38
 
@@ -41,7 +41,7 @@ export const base = defineModule({
41
41
  version: '0.1.0',
42
42
  groups: [
43
43
  defineGroup({ code: 'base.user', label: 'User' }),
44
- defineGroup({ code: 'base.admin', label: 'Administrator', implies: ['base.user'] }),
44
+ defineGroup({ code: 'base.admin', label: 'Administrator', implies: ['base.user'], administrator: true }),
45
45
  ],
46
46
  models: [ResUsers, ResCurrency, ResCompany],
47
47
  });
@@ -0,0 +1,2 @@
1
+ /** Registers the `.js` → `.ts` fallback once per process. */
2
+ export declare function allowJsSpecifiersForTs(): void;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Loading TypeScript module sources (feedback #16). Node runs `.ts` files by stripping types, but the `nodenext`
3
+ * convention writes imports between them as `./sale.js`. This resolve hook retries a missing relative `.js`
4
+ * specifier imported from a `.ts` file as `.ts`, so both spellings work without a loader.
5
+ */
6
+ import { registerHooks } from 'node:module';
7
+ let registered = false;
8
+ /** Registers the `.js` → `.ts` fallback once per process. */
9
+ export function allowJsSpecifiersForTs() {
10
+ if (registered)
11
+ return;
12
+ registered = true;
13
+ registerHooks({
14
+ resolve(specifier, context, nextResolve) {
15
+ try {
16
+ return nextResolve(specifier, context);
17
+ }
18
+ catch (error) {
19
+ const relative = specifier.startsWith('./') || specifier.startsWith('../');
20
+ const fromTs = context.parentURL?.endsWith('.ts') === true;
21
+ const missing = error.code === 'ERR_MODULE_NOT_FOUND';
22
+ if (relative && fromTs && missing && specifier.endsWith('.js'))
23
+ return nextResolve(`${specifier.slice(0, -3)}.ts`, context);
24
+ throw error;
25
+ }
26
+ },
27
+ });
28
+ }
@@ -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[]>;