shutro 0.1.0 → 0.2.1

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 (76) 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/apply.d.ts +5 -1
  70. package/dist/migrate/apply.js +20 -2
  71. package/dist/migrate/schema.js +40 -2
  72. package/dist/security/index.d.ts +24 -0
  73. package/dist/security/index.js +16 -0
  74. package/dist/sql/tag.d.ts +5 -0
  75. package/dist/sql/tag.js +29 -1
  76. package/package.json +1 -1
@@ -0,0 +1,58 @@
1
+ import { compile, sql } from '../../sql/index.js';
2
+ export const OUTBOX_CHANNEL = 'shutro_outbox';
3
+ export const JOB_CHANNEL = 'shutro_job';
4
+ const DDL = [
5
+ 'CREATE TABLE IF NOT EXISTS "shutro_outbox" ("id" bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, "topic" text NOT NULL, "payload" jsonb NOT NULL, "created_at" timestamp with time zone NOT NULL DEFAULT now(), "uid" bigint NOT NULL, "company_id" bigint NOT NULL, "groups" text[] NOT NULL DEFAULT \'{}\')',
6
+ 'CREATE INDEX IF NOT EXISTS "shutro_outbox_topic_id_idx" ON "shutro_outbox" ("topic", "id")',
7
+ 'CREATE TABLE IF NOT EXISTS "shutro_subscription" ("name" text PRIMARY KEY, "topic" text NOT NULL, "last_id" bigint NOT NULL DEFAULT 0, "attempts" integer NOT NULL DEFAULT 0, "retry_at" timestamp with time zone, "last_error" text)',
8
+ 'CREATE TABLE IF NOT EXISTS "shutro_dead_event" ("subscription" text NOT NULL, "event_id" bigint NOT NULL, "error" text NOT NULL, "at" timestamp with time zone NOT NULL DEFAULT now(), PRIMARY KEY ("subscription", "event_id"))',
9
+ 'CREATE TABLE IF NOT EXISTS "shutro_job" ("id" bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, "name" text NOT NULL, "payload" jsonb NOT NULL, "key" text, "state" text NOT NULL DEFAULT \'pending\', "run_at" timestamp with time zone NOT NULL DEFAULT now(), "attempts" integer NOT NULL DEFAULT 0, "max_attempts" integer NOT NULL DEFAULT 5, "locked_at" timestamp with time zone, "last_error" text, "created_at" timestamp with time zone NOT NULL DEFAULT now(), "done_at" timestamp with time zone, "uid" bigint NOT NULL, "company_id" bigint NOT NULL, "groups" text[] NOT NULL DEFAULT \'{}\')',
10
+ 'CREATE INDEX IF NOT EXISTS "shutro_job_due_idx" ON "shutro_job" ("state", "run_at")',
11
+ 'CREATE UNIQUE INDEX IF NOT EXISTS "shutro_job_key_idx" ON "shutro_job" ("key") WHERE "key" IS NOT NULL AND "state" IN (\'pending\', \'running\')',
12
+ ];
13
+ /** Statements creating the event and job tables (also created on first use). */
14
+ export function eventTableStatements() {
15
+ return DDL.map((text) => ({ text, params: [] }));
16
+ }
17
+ const ensured = new WeakSet();
18
+ /** Creates the tables once per driver (or per query function). */
19
+ export async function ensureEventTables(owner, query) {
20
+ if (ensured.has(owner))
21
+ return;
22
+ for (const text of DDL)
23
+ await query({ text, params: [] });
24
+ ensured.add(owner);
25
+ }
26
+ const TOPIC = /^[a-z][a-z0-9_]*(\.[a-z0-9_]+)*$/;
27
+ function assertName(kind, name) {
28
+ if (!TOPIC.test(name))
29
+ throw new TypeError(`${JSON.stringify(name)} is not a valid ${kind} name. Use dotted snake_case, e.g. 'invoice.posted'.`);
30
+ }
31
+ /** `env.emit`: inserts the event in the current transaction. */
32
+ export async function emitEvent(query, actor, topic, payload) {
33
+ assertName('topic', topic);
34
+ const [row] = await query(compile(sql `INSERT INTO shutro_outbox (topic, payload, uid, company_id, groups) VALUES (${topic}, (${sql.param(JSON.stringify(payload ?? null), 'text')})::jsonb, ${actor.uid}, ${actor.companyId}, ${sql.array([...actor.groups], 'text')}) RETURNING id`));
35
+ await query(compile(sql `SELECT pg_notify(${OUTBOX_CHANNEL}, ${topic})`));
36
+ return Number(row?.id);
37
+ }
38
+ /** `env.enqueue`: inserts the job in the current transaction. Returns its id, or `null` when deduplicated. */
39
+ export async function enqueueJob(query, actor, name, payload, options = {}) {
40
+ assertName('job', name);
41
+ const attempts = options.attempts ?? 5;
42
+ if (!Number.isInteger(attempts) || attempts < 1)
43
+ throw new TypeError('attempts must be a positive integer.');
44
+ const rows = await query(compile(sql `INSERT INTO shutro_job (name, payload, key, run_at, max_attempts, uid, company_id, groups)
45
+ VALUES (${name}, (${sql.param(JSON.stringify(payload ?? null), 'text')})::jsonb, ${options.key ?? null}, ${options.runAt ?? new Date(0)}, ${attempts}, ${actor.uid}, ${actor.companyId}, ${sql.array([...actor.groups], 'text')})
46
+ ON CONFLICT ("key") WHERE "key" IS NOT NULL AND "state" IN ('pending', 'running') DO NOTHING RETURNING id`));
47
+ await query(compile(sql `SELECT pg_notify(${JOB_CHANNEL}, ${name})`));
48
+ return rows[0] === undefined ? null : Number(rows[0].id);
49
+ }
50
+ /** Exponential backoff with a cap, in milliseconds (attempt 1 → 1 s, 2 → 2 s, … ≤ 10 min). */
51
+ export function backoffMs(attempt) {
52
+ return Math.min(600_000, 1000 * 2 ** Math.max(0, attempt - 1));
53
+ }
54
+ /** Releases jobs whose worker died while running them (locked longer than `staleMs`). */
55
+ export async function releaseStale(driver, staleMs) {
56
+ const rows = await driver.query(compile(sql `UPDATE shutro_job SET state = 'pending', locked_at = NULL WHERE state = 'running' AND locked_at < now() - make_interval(secs => ${staleMs / 1000}) RETURNING id`));
57
+ return rows.length;
58
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Event subscribers and job workers (RFC 0018 §7.2–§7.3). Both claim work with row locks (`SKIP LOCKED`), run the
3
+ * handler in a `run()` scope as the emitting / enqueuing user, and record success in the handler's transaction.
4
+ * Failures are retried with exponential backoff; after the attempts run out, events go to `shutro_dead_event` and
5
+ * jobs to state `dead`.
6
+ */
7
+ import type { Driver } from '../../driver-pg/index.js';
8
+ import type { Env, RunOptions } from '../env/env.js';
9
+ /** A committed event as subscribers receive it. */
10
+ export interface DeliveredEvent {
11
+ readonly id: number;
12
+ readonly topic: string;
13
+ readonly payload: unknown;
14
+ readonly createdAt: Date;
15
+ readonly uid: number;
16
+ readonly companyId: number;
17
+ }
18
+ /** A job as handlers receive it. */
19
+ export interface RunningJob {
20
+ readonly id: number;
21
+ readonly name: string;
22
+ readonly attempt: number;
23
+ readonly maxAttempts: number;
24
+ }
25
+ /** A subscriber or worker: `drain()` processes what is due now; `start()` keeps processing until `stop()`. */
26
+ export interface Worker {
27
+ /** Processes everything due now; resolves with the number of events / jobs handled (successfully or not). */
28
+ drain(): Promise<number>;
29
+ /** Processes in the background: woken by NOTIFY, and polling every `pollMs` for retries and scheduled work. */
30
+ start(): void;
31
+ stop(): Promise<void>;
32
+ }
33
+ /** What workers need from a Shutro instance. */
34
+ export interface WorkerHost {
35
+ readonly driver: Driver;
36
+ run<T>(options: RunOptions, fn: (env: Env) => Promise<T>): Promise<T>;
37
+ bootstrap<T>(options: {
38
+ readonly reason: string;
39
+ readonly company?: number;
40
+ }, fn: (env: Env) => Promise<T>): Promise<T>;
41
+ }
42
+ /**
43
+ * Delivers events of `topic` to `handler`, in id order, at least once; the cursor advances in the handler's
44
+ * transaction (exactly once for its database work). One active delivery per subscription name across processes.
45
+ */
46
+ export declare function subscribe(host: WorkerHost, name: string, topic: string, handler: (event: DeliveredEvent, env: Env) => Promise<void>, options?: {
47
+ readonly attempts?: number;
48
+ readonly pollMs?: number;
49
+ }): Worker;
50
+ /**
51
+ * Runs due jobs with the given handlers (any number of workers and processes: `FOR UPDATE SKIP LOCKED`). A job is
52
+ * marked done in its handler's transaction; a failure is retried with backoff until its attempts run out (`dead`).
53
+ */
54
+ export declare function work(host: WorkerHost, handlers: Readonly<Record<string, (payload: unknown, env: Env, job: RunningJob) => Promise<void>>>, options?: {
55
+ readonly pollMs?: number;
56
+ }): Worker;
@@ -0,0 +1,155 @@
1
+ import { compile, sql } from '../../sql/index.js';
2
+ import { SYSTEM_UID } from '../env/identity.js';
3
+ import { backoffMs, ensureEventTables, JOB_CHANNEL, OUTBOX_CHANNEL } from './events.js';
4
+ const SKIPPED = Symbol('skipped');
5
+ function message(error) {
6
+ return error instanceof Error ? error.message : String(error);
7
+ }
8
+ /** Runs `fn` as the actor of an event or job (the system for bootstrap-time work). */
9
+ function asActor(host, actor, reason, fn) {
10
+ if (actor.uid === SYSTEM_UID)
11
+ return host.bootstrap({ reason, ...(actor.companyId > 0 ? { company: actor.companyId } : {}) }, fn);
12
+ return host.run({ user: actor.uid, company: actor.companyId, groups: actor.groups, reason }, fn);
13
+ }
14
+ function loop(host, channel, pollMs, step) {
15
+ let running = false;
16
+ let current = Promise.resolve();
17
+ let timer;
18
+ let unlisten;
19
+ let wake = false;
20
+ const drain = async () => {
21
+ let n = 0;
22
+ while (await step())
23
+ n++;
24
+ return n;
25
+ };
26
+ const tick = () => {
27
+ if (!running)
28
+ return;
29
+ current = drain()
30
+ .catch(() => 0)
31
+ .finally(() => {
32
+ if (!running)
33
+ return;
34
+ if (wake) {
35
+ wake = false;
36
+ tick();
37
+ }
38
+ else
39
+ timer = setTimeout(tick, pollMs);
40
+ });
41
+ };
42
+ return {
43
+ drain,
44
+ start() {
45
+ if (running)
46
+ return;
47
+ running = true;
48
+ void host.driver
49
+ .listen(channel, () => {
50
+ wake = true;
51
+ if (timer !== undefined) {
52
+ clearTimeout(timer);
53
+ timer = undefined;
54
+ tick();
55
+ }
56
+ })
57
+ .then((stop) => {
58
+ unlisten = stop;
59
+ });
60
+ tick();
61
+ },
62
+ async stop() {
63
+ running = false;
64
+ if (timer !== undefined)
65
+ clearTimeout(timer);
66
+ await current;
67
+ await unlisten?.();
68
+ },
69
+ };
70
+ }
71
+ /**
72
+ * Delivers events of `topic` to `handler`, in id order, at least once; the cursor advances in the handler's
73
+ * transaction (exactly once for its database work). One active delivery per subscription name across processes.
74
+ */
75
+ export function subscribe(host, name, topic, handler, options = {}) {
76
+ const attempts = options.attempts ?? 10;
77
+ const step = async () => {
78
+ await ensureEventTables(host.driver, (q) => host.driver.query(q));
79
+ await host.driver.query(compile(sql `INSERT INTO shutro_subscription (name, topic) VALUES (${name}, ${topic}) ON CONFLICT (name) DO NOTHING`));
80
+ const [sub] = await host.driver.query(compile(sql `SELECT last_id, attempts, (retry_at IS NULL OR retry_at <= now()) AS due FROM shutro_subscription WHERE name = ${name}`));
81
+ if (sub === undefined || !sub.due)
82
+ return false;
83
+ const lastId = Number(sub.last_id);
84
+ const [row] = await host.driver.query(compile(sql `SELECT id, payload, created_at, uid, company_id, groups FROM shutro_outbox WHERE topic = ${topic} AND id > ${lastId} ORDER BY id LIMIT 1`));
85
+ if (row === undefined)
86
+ return false;
87
+ const event = {
88
+ id: Number(row.id),
89
+ topic,
90
+ payload: row.payload,
91
+ createdAt: row.created_at,
92
+ uid: Number(row.uid),
93
+ companyId: Number(row.company_id),
94
+ };
95
+ try {
96
+ await asActor(host, { uid: event.uid, companyId: event.companyId, groups: row.groups }, `event ${name}`, async (env) => {
97
+ const [locked] = await env.sql `SELECT last_id FROM shutro_subscription WHERE name = ${name} FOR UPDATE SKIP LOCKED`;
98
+ if (locked === undefined || Number(locked.last_id) !== lastId)
99
+ throw SKIPPED; // another process has it
100
+ await handler(event, env);
101
+ await env.sql `UPDATE shutro_subscription SET last_id = ${event.id}, attempts = 0, retry_at = NULL, last_error = NULL WHERE name = ${name}`;
102
+ });
103
+ return true;
104
+ }
105
+ catch (error) {
106
+ if (error === SKIPPED)
107
+ return false;
108
+ const tries = sub.attempts + 1;
109
+ if (tries >= attempts) {
110
+ await host.driver.transaction({ isolation: 'read committed' }, async (conn) => {
111
+ await conn.query(compile(sql `INSERT INTO shutro_dead_event (subscription, event_id, error) VALUES (${name}, ${event.id}, ${message(error)}) ON CONFLICT DO NOTHING`));
112
+ await conn.query(compile(sql `UPDATE shutro_subscription SET last_id = ${event.id}, attempts = 0, retry_at = NULL, last_error = ${message(error)} WHERE name = ${name}`));
113
+ });
114
+ return true;
115
+ }
116
+ await host.driver.query(compile(sql `UPDATE shutro_subscription SET attempts = ${tries}, retry_at = now() + make_interval(secs => ${backoffMs(tries) / 1000}), last_error = ${message(error)} WHERE name = ${name}`));
117
+ return false;
118
+ }
119
+ };
120
+ return loop(host, OUTBOX_CHANNEL, options.pollMs ?? 1000, step);
121
+ }
122
+ /**
123
+ * Runs due jobs with the given handlers (any number of workers and processes: `FOR UPDATE SKIP LOCKED`). A job is
124
+ * marked done in its handler's transaction; a failure is retried with backoff until its attempts run out (`dead`).
125
+ */
126
+ export function work(host, handlers, options = {}) {
127
+ const names = Object.keys(handlers);
128
+ const step = async () => {
129
+ await ensureEventTables(host.driver, (q) => host.driver.query(q));
130
+ const [job] = await host.driver.query(compile(sql `UPDATE shutro_job SET state = 'running', attempts = attempts + 1, locked_at = now()
131
+ WHERE id = (SELECT id FROM shutro_job WHERE state = 'pending' AND run_at <= now() AND name = ANY(${sql.array(names, 'text')}) ORDER BY run_at, id LIMIT 1 FOR UPDATE SKIP LOCKED)
132
+ RETURNING id, name, payload, attempts, max_attempts, uid, company_id, groups`));
133
+ if (job === undefined)
134
+ return false;
135
+ const id = Number(job.id);
136
+ const handler = handlers[job.name];
137
+ try {
138
+ await asActor(host, { uid: Number(job.uid), companyId: Number(job.company_id), groups: job.groups }, `job ${job.name}`, async (env) => {
139
+ await handler?.(job.payload, env, {
140
+ id,
141
+ name: job.name,
142
+ attempt: job.attempts,
143
+ maxAttempts: job.max_attempts,
144
+ });
145
+ await env.sql `UPDATE shutro_job SET state = 'done', done_at = now(), locked_at = NULL, last_error = NULL WHERE id = ${id}`;
146
+ });
147
+ }
148
+ catch (error) {
149
+ const dead = job.attempts >= job.max_attempts;
150
+ await host.driver.query(compile(sql `UPDATE shutro_job SET state = ${dead ? 'dead' : 'pending'}, locked_at = NULL, last_error = ${message(error)}, run_at = now() + make_interval(secs => ${backoffMs(job.attempts) / 1000}) WHERE id = ${id}`));
151
+ }
152
+ return true;
153
+ };
154
+ return loop(host, JOB_CHANNEL, options.pollMs ?? 1000, step);
155
+ }
@@ -8,23 +8,30 @@
8
8
  */
9
9
  export { type AuditAction, type AuditEntry, auditTableStatements, readTrail, type TrailFilter, } from '../audit/index.js';
10
10
  export { isTranslations, mergeTranslation, resolveTranslation, type Translations, } from '../i18n/index.js';
11
- export { type AccessSpec, createKeyRing, defineGroup, EncryptionError, type FieldGroups, type FieldGroupsInput, type GroupDefinition, type KeyRing, type Perm, type RulePerm, type RuleSpec, SecurityDefinitionError, } from '../security/index.js';
11
+ export { type AccessSpec, createKeyRing, defineGroup, definePermission, EncryptionError, type FieldGroups, type FieldGroupsInput, type GroupDefinition, type KeyRing, type Perm, type PermissionDefinition, type RulePerm, type RuleSpec, SecurityDefinitionError, } from '../security/index.js';
12
12
  export { defineSequence, InvalidSequenceError, type SequenceDefinition, type SequenceInput, type SequenceReset, } from '../sequence/index.js';
13
+ export { type CompiledSql, compile, type SqlFragment, sql } from '../sql/index.js';
13
14
  export { buildComputeGraph, type ComputedField, type ComputeGraph, type PathStep, type Trigger, } from './compute/graph.js';
15
+ export { type DataRecord, type DataRef, isRef, override, record, ref, } from './data/data.js';
16
+ export { type DataLoadResult, EXTERNAL_ID_TABLE, externalIdTableStatements, loadData, } from './data/load.js';
14
17
  export type { VerifiedIdentity } from './env/env.js';
15
- export { createShutro, Env, type Flags, type Hook, type RunOptions, type ScopeStats, type Shutro, type ShutroOptions, } from './env/env.js';
16
- export type { Identity, ResolvedIdentity } from './env/identity.js';
18
+ export { type BootstrapOptions, createShutro, Env, type Flags, type Hook, type RunOptions, type ScopeStats, type SecurityAdmin, type Shutro, type ShutroOptions, } from './env/env.js';
19
+ export { type Identity, type ResolvedIdentity, SYSTEM_UID } from './env/identity.js';
17
20
  export { createInspector, type InspectedQuery, type Inspector, type InspectorOptions, type InspectorWarning, } from './env/inspector.js';
18
21
  export { assertTimeZone, calendarDateIn } from './env/time.js';
19
- export { AccessError, CompanyNotAllowedError, ComputeAssignmentError, ComputeCycleError, ConcurrentUpdateError, ConstraintError, ConstraintViolationError, CrossCompanyError, CurrencyMismatchError, DivisionByZeroError, DuplicateModelError, DuplicateModuleError, EmptyMoneySumError, ExtensionConflictError, FieldNotLoadedError, FlagNotAllowedError, IncompatibleUomCategoryError, InvalidAllocationError, InvalidCurrencyError, InvalidDecimalError, InvalidDependsPathError, InvalidDomainError, InvalidExtensionError, InvalidFieldError, InvalidIdentityError, InvalidModelError, InvalidModuleError, InvalidRelationError, InvalidTransitionError, InvalidUomError, MissingRateError, MissingRecordError, NoEnvironmentError, NonIntegerNumberError, NoRegistryError, RecomputeLimitError, ShutroError, type ShutroErrorCode, SingletonError, type SqlConstraintKind, TransactionScopeError, TransitionGuardError, UndeclaredDependencyError, UnknownModelError, UnknownSequenceError, UomMismatchError, ValidationError, } from './errors.js';
22
+ export { AccessError, CompanyNotAllowedError, ComputeAssignmentError, ComputeCycleError, ConcurrentUpdateError, ConstraintError, ConstraintViolationError, CrossCompanyError, CurrencyMismatchError, DivisionByZeroError, DuplicateModelError, DuplicateModuleError, EmptyMoneySumError, ExtensionConflictError, FieldNotLoadedError, FlagNotAllowedError, IncompatibleUomCategoryError, InvalidAllocationError, InvalidCurrencyError, InvalidDecimalError, InvalidDependsPathError, InvalidDomainError, InvalidExtensionError, InvalidFieldError, InvalidIdentityError, InvalidModelError, InvalidModuleError, InvalidRelationError, InvalidTransitionError, InvalidUomError, MissingRateError, MissingRecordError, NoEnvironmentError, NonIntegerNumberError, NoRegistryError, RecomputeLimitError, ShutroError, type ShutroErrorCode, SingletonError, type SqlConstraintKind, StaleRecordError, TransactionScopeError, TransitionGuardError, UndeclaredDependencyError, UnknownExternalIdError, UnknownModelError, UnknownSequenceError, UomMismatchError, ValidationError, } from './errors.js';
23
+ export { type EnqueueOptions, eventTableStatements, JOB_CHANNEL, OUTBOX_CHANNEL, releaseStale, } from './events/events.js';
24
+ export type { DeliveredEvent, RunningJob, Worker } from './events/workers.js';
20
25
  export type { CreateOf, FlagsOfField, ReadOf, WriteOf } from './model/faces.js';
21
26
  export type { SequenceFieldOptions, TextWrite } from './model/field.js';
22
- export { type BinaryField, type BinaryOptions, type CharField, type CharOptions, type CommonOptions, type ComputeFn, type DecimalField, type DecimalOptions, type Field, type FieldBase, type FieldBuilders, type FieldFlags, type FieldKind, type FieldOverrideChanges, type FieldTypes, type FlagsOf, type FloatField, f, type HtmlOptions, type IdField, type IndexKind, type InverseFn, isField, type JsonField, type JsonOptions, type Many2manyField, type Many2manyOptions, type Many2oneField, type Many2oneOptions, type MonetaryField, type MonetaryOptions, type OnDelete, type One2manyField, type QuantityField, type QuantityOptions, type ScalarField, type SelectionField, type SelectionOptions, type StateField, type StateHooks, type StateOptions, type StateSpec, type TextOptions, type Transition, type X2ManyOptions, } from './model/field.js';
27
+ export { type BinaryField, type BinaryOptions, type CharField, type CharOptions, type CommonOptions, type ComputeFn, type DecimalField, type DecimalOptions, type Field, type FieldBase, type FieldBuilders, type FieldFlags, type FieldKind, type FieldOverrideChanges, type FieldTypes, type FlagsOf, type FloatField, f, type HtmlOptions, type IdField, type IndexKind, type InverseFn, isField, type JsonField, type JsonOptions, type Many2manyField, type Many2manyOptions, type Many2oneField, type Many2oneOptions, type MonetaryField, type MonetaryOptions, type OnDelete, type One2manyField, type QuantityField, type QuantityOptions, type ScalarField, type SearchFn, type SelectionField, type SelectionOptions, type StateField, type StateHooks, type StateOptions, type StateSpec, type TextOptions, type Transition, type X2ManyOptions, } from './model/field.js';
23
28
  export type * as F from './model/generated.js';
24
29
  export { asId, type Id, type X2ManyCommands } from './model/id.js';
25
30
  export type { OnchangeFn } from './model/model.js';
26
- export { type ActiveField, type AnyModel, type CompanyField, type CompanyScope, type ConstraintSpec, defineModel, type FieldDescription, type FieldRules, type FieldsRecord, humanize, type ImplicitFields, type ImplicitFieldsBase, type IndexSpec, isModel, type MethodsRecord, type Model, type ModelDefinition, type ModelDescription, type ModelFields, type OrderSpec, type OrderTerm, RESERVED_KEYS, type ReservedKey, type ResolvedConstraint, type ResolvedIndex, type ResolvedSqlConstraint, type SqlCheckConstraint, type SqlUniqueConstraint, snakeCase, type TransitionMethods, transitionOf, } from './model/model.js';
31
+ export { type ActiveField, type AnyModel, type BackdateSpec, type CompanyField, type CompanyScope, type ConstraintSpec, defineModel, type FieldDescription, type FieldRules, type FieldsRecord, type HierarchySpec, humanize, type ImplicitFields, type ImplicitFieldsBase, type IndexSpec, isModel, type MethodsRecord, type Model, type ModelDefinition, type ModelDescription, type ModelFields, type OrderSpec, type OrderTerm, RESERVED_KEYS, type ReservedKey, type ResolvedConstraint, type ResolvedIndex, type ResolvedSqlConstraint, type SqlCheckConstraint, type SqlUniqueConstraint, snakeCase, type TransitionMethods, transitionOf, } from './model/model.js';
27
32
  export { type PartitionBound, type PartitionSpec, partitionStatements, rangePartitions, } from './model/partition.js';
33
+ export { related, relatedPath } from './model/related.js';
34
+ export { type DefinitionHelpers, definitions, type LoadedFrom, type PathLoaded, } from './model/typed.js';
28
35
  export { type Currency, type CurrencyInput, defineCurrency, sameCurrency, } from './money/currency.js';
29
36
  export { Decimal, type DecimalInput, toDecimal } from './money/decimal.js';
30
37
  export type { Conversion, ConvertOptions, Fx, PreparedRates } from './money/fx.js';
@@ -35,9 +42,10 @@ export { coalesceAudit, isTracked } from './recordset/audit.js';
35
42
  export { type JunctionTable, junctionTable } from './recordset/relations.js';
36
43
  export { modelPolicies, rlsStatements, ruleCondition } from './recordset/rls.js';
37
44
  export { UNNUMBERED } from './recordset/sequences.js';
38
- export type { Access, ComputedKeys, ComputeRec, ComputeSet, CreateValues, DefaultLoaded, Defaults, Domain, Draft, DraftValue, FieldsOf, IdOnly, ListKeys, ListLoaded, LoadedKeys, LoadSpec, Many2oneKeys, Merge, MethodsOf, ModelName, ModelRef, NotLoaded, OnchangeInput, OnchangeResult, PendingSet, PlainRow, Rec, RecordSet, RecordSetApi, RelKeys, ScalarKeys, SearchOrder, SearchQuery, SequenceKeys, Target, ToLoaded, TranslatedKeys, WriteValues, X2ManyKeys, } from './recordset/types.js';
45
+ export type { Access, AggregateQuery, AggregateRow, ComputedKeys, ComputeRec, ComputeSet, CreateValues, DefaultLoaded, Defaults, Domain, Draft, DraftValue, FieldsOf, Granularity, GroupKey, IdOnly, ListKeys, ListLoaded, LoadedKeys, LoadSpec, Many2oneKeys, Measure, Merge, MethodsOf, ModelName, ModelRef, NotLoaded, OnchangeInput, OnchangeResult, PendingSet, PlainRow, Rec, RecordSet, RecordSetApi, RelKeys, ScalarKeys, SearchOrder, SearchQuery, SequenceKeys, SummableKeys, SumOf, Target, ToLoaded, TranslatedKeys, WriteValues, X2ManyKeys, } from './recordset/types.js';
39
46
  export { copyField } from './recordset/writes.js';
40
- export { columnDefault, createTableStatements } from './registry/ddl.js';
47
+ export { columnDefault, createTableStatements, historyStatements, historyTable, } from './registry/ddl.js';
41
48
  export { type AnyExtension, type Extension, type ExtensionDefinition, extendModel, type FieldOverride, isExtension, type OverrideFn, type Replacement, replace, } from './registry/extension.js';
42
49
  export { compareVersions, type DataMigration, defineModule, isModule, type MigrationContext, type Module, type ModuleBase, type ModuleDefinition, } from './registry/module.js';
43
- export { buildRegistry, type MethodLayer, type Origin, type RegisteredModel, type Registry, type RegistryModelDescription, type RegistryOptions, type SchemaOfModule, type SchemaOfModules, targetOf, } from './registry/registry.js';
50
+ export { buildRegistry, type MethodLayer, type Origin, type RegisteredModel, type Registry, type RegistryModelDescription, type RegistryOptions, type SchemaOfModule, type SchemaOfModules, type SecurityOptions, targetOf, } from './registry/registry.js';
51
+ export { loadRuntimeSecurity, type RuntimeRole, type RuntimeRule, type RuntimeSecurity, runtimeSecurityStatements, SECURITY_CHANNEL, } from './security/runtime.js';
@@ -8,17 +8,24 @@
8
8
  */
9
9
  export { auditTableStatements, readTrail, } from '../audit/index.js';
10
10
  export { isTranslations, mergeTranslation, resolveTranslation, } from '../i18n/index.js';
11
- export { createKeyRing, defineGroup, EncryptionError, SecurityDefinitionError, } from '../security/index.js';
11
+ export { createKeyRing, defineGroup, definePermission, EncryptionError, SecurityDefinitionError, } from '../security/index.js';
12
12
  export { defineSequence, InvalidSequenceError, } from '../sequence/index.js';
13
+ export { compile, sql } from '../sql/index.js';
13
14
  export { buildComputeGraph, } from './compute/graph.js';
15
+ export { isRef, override, record, ref, } from './data/data.js';
16
+ export { EXTERNAL_ID_TABLE, externalIdTableStatements, loadData, } from './data/load.js';
14
17
  export { createShutro, Env, } from './env/env.js';
18
+ export { SYSTEM_UID } from './env/identity.js';
15
19
  export { createInspector, } from './env/inspector.js';
16
20
  export { assertTimeZone, calendarDateIn } from './env/time.js';
17
- export { AccessError, CompanyNotAllowedError, ComputeAssignmentError, ComputeCycleError, ConcurrentUpdateError, ConstraintError, ConstraintViolationError, CrossCompanyError, CurrencyMismatchError, DivisionByZeroError, DuplicateModelError, DuplicateModuleError, EmptyMoneySumError, ExtensionConflictError, FieldNotLoadedError, FlagNotAllowedError, IncompatibleUomCategoryError, InvalidAllocationError, InvalidCurrencyError, InvalidDecimalError, InvalidDependsPathError, InvalidDomainError, InvalidExtensionError, InvalidFieldError, InvalidIdentityError, InvalidModelError, InvalidModuleError, InvalidRelationError, InvalidTransitionError, InvalidUomError, MissingRateError, MissingRecordError, NoEnvironmentError, NonIntegerNumberError, NoRegistryError, RecomputeLimitError, ShutroError, SingletonError, TransactionScopeError, TransitionGuardError, UndeclaredDependencyError, UnknownModelError, UnknownSequenceError, UomMismatchError, ValidationError, } from './errors.js';
21
+ export { AccessError, CompanyNotAllowedError, ComputeAssignmentError, ComputeCycleError, ConcurrentUpdateError, ConstraintError, ConstraintViolationError, CrossCompanyError, CurrencyMismatchError, DivisionByZeroError, DuplicateModelError, DuplicateModuleError, EmptyMoneySumError, ExtensionConflictError, FieldNotLoadedError, FlagNotAllowedError, IncompatibleUomCategoryError, InvalidAllocationError, InvalidCurrencyError, InvalidDecimalError, InvalidDependsPathError, InvalidDomainError, InvalidExtensionError, InvalidFieldError, InvalidIdentityError, InvalidModelError, InvalidModuleError, InvalidRelationError, InvalidTransitionError, InvalidUomError, MissingRateError, MissingRecordError, NoEnvironmentError, NonIntegerNumberError, NoRegistryError, RecomputeLimitError, ShutroError, SingletonError, StaleRecordError, TransactionScopeError, TransitionGuardError, UndeclaredDependencyError, UnknownExternalIdError, UnknownModelError, UnknownSequenceError, UomMismatchError, ValidationError, } from './errors.js';
22
+ export { eventTableStatements, JOB_CHANNEL, OUTBOX_CHANNEL, releaseStale, } from './events/events.js';
18
23
  export { f, isField, } from './model/field.js';
19
24
  export { asId } from './model/id.js';
20
25
  export { defineModel, humanize, isModel, RESERVED_KEYS, snakeCase, transitionOf, } from './model/model.js';
21
26
  export { partitionStatements, rangePartitions, } from './model/partition.js';
27
+ export { related, relatedPath } from './model/related.js';
28
+ export { definitions, } from './model/typed.js';
22
29
  export { defineCurrency, sameCurrency, } from './money/currency.js';
23
30
  export { Decimal, toDecimal } from './money/decimal.js';
24
31
  export { Money } from './money/money.js';
@@ -28,7 +35,8 @@ export { junctionTable } from './recordset/relations.js';
28
35
  export { modelPolicies, rlsStatements, ruleCondition } from './recordset/rls.js';
29
36
  export { UNNUMBERED } from './recordset/sequences.js';
30
37
  export { copyField } from './recordset/writes.js';
31
- export { columnDefault, createTableStatements } from './registry/ddl.js';
38
+ export { columnDefault, createTableStatements, historyStatements, historyTable, } from './registry/ddl.js';
32
39
  export { extendModel, isExtension, replace, } from './registry/extension.js';
33
40
  export { compareVersions, defineModule, isModule, } from './registry/module.js';
34
41
  export { buildRegistry, targetOf, } from './registry/registry.js';
42
+ export { loadRuntimeSecurity, runtimeSecurityStatements, SECURITY_CHANNEL, } from './security/runtime.js';
@@ -73,6 +73,12 @@ export interface FieldBase<K extends FieldKind, R, W, Fl extends FieldFlags> {
73
73
  readonly translate: boolean;
74
74
  /** Stored encrypted with the application keys (RFC 0014 §7.6); char / text only. */
75
75
  readonly encrypted: boolean;
76
+ /** One value per company (a `jsonb` map by company id); reads and writes see the current company's value. */
77
+ readonly companyDependent: boolean;
78
+ /** How filters on this non-stored computed field translate to stored fields. */
79
+ readonly search: SearchFn | undefined;
80
+ /** The column type of one value (`pgType` is `jsonb` for company-dependent fields). */
81
+ readonly valueType: string;
76
82
  /** Phantom. Never present at runtime. */
77
83
  readonly '~types'?: FieldTypes<R, W, Fl>;
78
84
  }
@@ -97,7 +103,20 @@ export interface CommonOptions<V> {
97
103
  /** Inline batch function, or the key of a model method shared by several fields. */
98
104
  readonly compute?: ComputeFn | string;
99
105
  readonly inverse?: InverseFn;
106
+ /**
107
+ * One value per company (Odoo `company_dependent`): reads, writes, filters and sorts use the current company's
108
+ * value, falling back to `default`. Not required, stored, computed, translated or encrypted.
109
+ */
110
+ readonly companyDependent?: boolean;
111
+ /**
112
+ * Makes a non-stored computed field searchable (Odoo `search=`): returns the domain on stored fields that matches
113
+ * `operator` and `value` (`'eq'` for a plain value). Called while the search is compiled.
114
+ * @example search: (op, value) => (op === 'eq' && value === true ? { price: { gt: '100' } } : { price: { lte: '100' } })
115
+ */
116
+ readonly search?: SearchFn;
100
117
  }
118
+ /** Translates a filter on a non-stored computed field into a domain on stored fields. */
119
+ export type SearchFn = (operator: string, value: unknown) => Readonly<Record<string, unknown>>;
101
120
  /** Options of text-like fields. */
102
121
  export interface TextOptions extends CommonOptions<string> {
103
122
  /** Store per-language values as JSONB (RFC 0001 §7.3). */
@@ -157,6 +176,8 @@ export interface Transition<S extends string> {
157
176
  readonly message?: string;
158
177
  readonly before?: (records: never) => unknown;
159
178
  readonly after?: (records: never) => unknown;
179
+ /** A feature permission (`definePermission`) the user needs to run this transition (RFC 0014 §7.9). */
180
+ readonly requires?: string;
160
181
  }
161
182
  /** Options of `f.state`. */
162
183
  export interface StateOptions<S extends Record<string, string | StateSpec>, T extends Record<string, Transition<keyof S & string>>> {
@@ -181,6 +202,11 @@ export interface Many2oneOptions<T extends string> extends CommonOptions<Id<T>>
181
202
  readonly ondelete?: OnDelete;
182
203
  /** The target must be shared or in the same company as the record (RFC 0003 §7.4). The model must be companyScoped. */
183
204
  readonly checkCompany?: boolean;
205
+ /**
206
+ * `false`: no database foreign key (e.g. the target is partitioned, RFC 0015). The ORM checks that written ids
207
+ * exist; deleting the target is not restricted by the database, so `ondelete` cannot be set.
208
+ */
209
+ readonly foreignKey?: boolean;
184
210
  }
185
211
  /** Options of x2many fields (never stored as a column). */
186
212
  export interface X2ManyOptions<T extends string> extends Omit<CommonOptions<X2ManyCommands<T>>, 'store' | 'index' | 'tracking'> {
@@ -248,6 +274,8 @@ export interface Many2oneField<T extends string, Fl extends FieldFlags> extends
248
274
  readonly target: T;
249
275
  readonly ondelete: OnDelete;
250
276
  readonly checkCompany: boolean;
277
+ /** `false` when the column has no database foreign key. */
278
+ readonly foreignKey: boolean;
251
279
  }
252
280
  /** `f.one2many` descriptor. */
253
281
  export interface One2manyField<T extends string, Fl extends FieldFlags> extends FieldBase<'one2many', {
@@ -441,6 +469,11 @@ export interface FieldOverrideChanges {
441
469
  readonly transitions?: Readonly<Record<string, Transition<string>>>;
442
470
  readonly stateHooks?: Readonly<Record<string, StateHooks>>;
443
471
  }
472
+ /**
473
+ * @internal The child's copy of a parent field under delegation (`delegates`): a non-stored related field through
474
+ * the delegate many2one, writable unless the parent field is readonly.
475
+ */
476
+ export declare function delegatedField<F extends Field>(field: F, path: string): F;
444
477
  /** @internal Returns a new descriptor with `changes` applied; the registry validates them first. */
445
478
  export declare function overrideField<F extends Field>(field: F, changes: FieldOverrideChanges): F;
446
479
  export {};
@@ -5,6 +5,7 @@
5
5
  import { normalizeFieldGroups } from '../../security/index.js';
6
6
  import { InvalidFieldError, ShutroError } from '../errors.js';
7
7
  import { toDecimal } from '../money/decimal.js';
8
+ import { related } from './related.js';
8
9
  // ------------------------------------------------------------------------------------------------ validation
9
10
  /** SQL-level names (columns, relation tables): snake_case. */
10
11
  const IDENTIFIER = /^[a-z_][a-z0-9_]*$/;
@@ -91,6 +92,16 @@ function normalize(options, defaults = {}) {
91
92
  throw new InvalidFieldError('A sequence needs a code.', "Pass sequence: 'sale.order' or { code: 'account.move', gapless: true }.");
92
93
  }
93
94
  const computed = compute !== undefined;
95
+ if (options.search !== undefined &&
96
+ (!computed || options.store === true || typeof options.search !== 'function'))
97
+ throw new InvalidFieldError('`search` applies to non-stored computed fields.', 'Stored fields are searched directly; give non-stored computes search(operator, value) => domain.');
98
+ if (options.companyDependent === true &&
99
+ (options.required === true ||
100
+ computed ||
101
+ options.translate === true ||
102
+ options.encrypted === true ||
103
+ sequence !== undefined))
104
+ throw new InvalidFieldError('A company-dependent field cannot be required, computed, translated, encrypted or numbered.', 'Give it a default instead of required; companies without a value read the default.');
94
105
  return {
95
106
  label: options.label,
96
107
  help: options.help,
@@ -114,9 +125,34 @@ function normalize(options, defaults = {}) {
114
125
  sequence,
115
126
  translate: options.translate ?? false,
116
127
  encrypted: options.encrypted ?? false,
128
+ companyDependent: options.companyDependent ?? false,
129
+ search: options.search,
117
130
  };
118
131
  }
119
- function make(descriptor) {
132
+ const COMPANY_DEPENDENT_KINDS = new Set([
133
+ 'char',
134
+ 'text',
135
+ 'html',
136
+ 'integer',
137
+ 'float',
138
+ 'decimal',
139
+ 'boolean',
140
+ 'date',
141
+ 'selection',
142
+ 'many2one',
143
+ ]);
144
+ function make(input) {
145
+ const d = input;
146
+ let descriptor = input;
147
+ if (d.valueType === undefined && d.pgType !== undefined) {
148
+ if (d.companyDependent === true && !COMPANY_DEPENDENT_KINDS.has(d.kind ?? ''))
149
+ throw new InvalidFieldError(`A ${d.kind} field cannot be company-dependent.`, 'Company-dependent fields are char, text, html, integer, float, decimal, boolean, date, selection or many2one.');
150
+ descriptor = {
151
+ ...input,
152
+ valueType: d.kind === 'many2one' ? 'bigint' : d.pgType,
153
+ pgType: d.companyDependent === true ? 'jsonb' : d.pgType,
154
+ };
155
+ }
120
156
  const frozen = Object.freeze(descriptor);
121
157
  created.add(frozen);
122
158
  return frozen;
@@ -337,6 +373,9 @@ export const f = {
337
373
  assertModelName(target, 'many2one');
338
374
  const opts = options ?? {};
339
375
  const ondelete = opts.ondelete ?? 'restrict';
376
+ if (opts.foreignKey === false && opts.ondelete !== undefined) {
377
+ throw new InvalidFieldError('A many2one with foreignKey: false cannot set ondelete: nothing in the database enforces it.', 'Remove ondelete, or keep the foreign key.');
378
+ }
340
379
  if (opts.required === true && ondelete === 'set null') {
341
380
  throw new InvalidFieldError("A required many2one cannot use ondelete: 'set null'.", "Use 'restrict' (default) or 'cascade', or make the field optional.");
342
381
  }
@@ -347,6 +386,7 @@ export const f = {
347
386
  target,
348
387
  ondelete,
349
388
  checkCompany: opts.checkCompany ?? false,
389
+ foreignKey: opts.foreignKey !== false,
350
390
  });
351
391
  },
352
392
  /** The records of `target` whose `inverse` many2one points here. */
@@ -388,6 +428,29 @@ export function withDefaultLabel(field, label) {
388
428
  return field;
389
429
  return make({ ...field, label });
390
430
  }
431
+ /**
432
+ * @internal The child's copy of a parent field under delegation (`delegates`): a non-stored related field through
433
+ * the delegate many2one, writable unless the parent field is readonly.
434
+ */
435
+ export function delegatedField(field, path) {
436
+ const r = field.readonly ? related(path) : related(path, { writable: true });
437
+ return make({
438
+ ...field,
439
+ computed: true,
440
+ store: false,
441
+ compute: r.compute,
442
+ inverse: 'inverse' in r ? r.inverse : undefined,
443
+ depends: r.depends,
444
+ readonly: field.readonly,
445
+ required: false,
446
+ default: undefined,
447
+ sequence: undefined,
448
+ index: undefined,
449
+ column: undefined,
450
+ tracking: false,
451
+ delegated: path.slice(0, path.indexOf('.')),
452
+ });
453
+ }
391
454
  /** @internal Returns a new descriptor with `changes` applied; the registry validates them first. */
392
455
  export function overrideField(field, changes) {
393
456
  const next = { ...field };
@@ -67,9 +67,11 @@ type Contributions<Mod> = Mod extends {
67
67
  * The `methods` that module `Mod` (its models and extensions) declares on model `N`. Generated views intersect one
68
68
  * of these per contributing module, so method types come from the sources without a compiler API.
69
69
  */
70
- export type Methods<Mod, N extends string> = UnionToIntersection<Extract<Contributions<Mod>, {
70
+ export type Methods<Mod, N extends string> = OrEmpty<UnionToIntersection<Extract<Contributions<Mod>, {
71
71
  readonly name: N;
72
72
  }> extends infer C ? C extends {
73
73
  readonly methods: infer M;
74
- } ? M : never : never>;
74
+ } ? M : never : never>>;
75
+ /** `{}` instead of `unknown` when a module declares no method, so generated method interfaces can extend it. */
76
+ type OrEmpty<X> = unknown extends X ? Record<never, never> : X;
75
77
  export {};
@@ -124,6 +124,22 @@ export interface ConstraintSpec {
124
124
  readonly check: (records: never) => unknown;
125
125
  readonly message: string | ((failing: never) => string);
126
126
  }
127
+ /** The `hierarchy` option of a model. */
128
+ export interface HierarchySpec<K extends string = string> {
129
+ /** The many2one to the parent record (same model). */
130
+ readonly parent: K;
131
+ /** A readonly char field holding the materialized path (`'1/5/9/'`), maintained by the engine. */
132
+ readonly path: K;
133
+ }
134
+ /** The `backdate` option of a model. */
135
+ export interface BackdateSpec<K extends string = string> {
136
+ /** The document date (`date` or `datetime`). */
137
+ readonly field: K;
138
+ /** The feature permission (`definePermission`) that allows earlier dates. */
139
+ readonly permission: string;
140
+ /** Days before today still allowed without the permission (default 0: today and later). */
141
+ readonly graceDays?: number;
142
+ }
127
143
  /** An onchange handler (RFC 0009 §7.3): receives the draft and the environment. Typed by the recordset layer. */
128
144
  export type OnchangeFn = (draft: never, env: never) => void | Promise<void>;
129
145
  /** The argument of {@link defineModel} after `name`. */
@@ -142,6 +158,26 @@ export interface ModelDefinition<Fs extends FieldsRecord, Ms extends MethodsReco
142
158
  readonly companyScoped?: C;
143
159
  /** Fields whose changes are tracked in the audit trail. */
144
160
  readonly tracking?: readonly ModelKeys<Fs, A, C>[];
161
+ /**
162
+ * Back-dated entries need a permission (RFC 0014 §7.9): creating a record, or changing `field`, to a date before
163
+ * today (in the user's time zone) minus `graceDays` requires the feature permission `permission`.
164
+ */
165
+ readonly backdate?: BackdateSpec<ModelKeys<Fs, A, C>>;
166
+ /**
167
+ * A tree (categories, accounts, locations): `parent` is a many2one to this model, `path` a readonly char field the
168
+ * engine maintains (`'1/5/9/'`), so `childOf` / `parentOf` filters are prefix matches on an index.
169
+ */
170
+ readonly hierarchy?: HierarchySpec<ModelKeys<Fs, A, C>>;
171
+ /**
172
+ * Delegation (Odoo `_inherits`): each listed key is a required many2one whose target's fields the records expose
173
+ * as their own (read, write, filter), stored in the target. Creating a record creates its target record.
174
+ */
175
+ readonly delegates?: readonly ModelKeys<Fs, A, C>[];
176
+ /**
177
+ * Keep every version of the rows (RFC 0018 §7.4): a trigger archives the old row into `<table>_history`, and
178
+ * `env.asOf(instant, fn)` reads the model as it was then.
179
+ */
180
+ readonly history?: boolean;
145
181
  readonly indexes?: readonly IndexSpec<ModelKeys<Fs, A, C>>[];
146
182
  readonly sqlConstraints?: Readonly<Record<string, SqlUniqueConstraint<ModelKeys<Fs, A, C>> | SqlCheckConstraint>>;
147
183
  readonly constraints?: Readonly<Record<string, ConstraintSpec>>;
@@ -231,6 +267,10 @@ export interface Model<N extends string, Fs extends FieldsRecord, Ms extends Met
231
267
  readonly archivable: boolean;
232
268
  readonly companyScoped: CompanyScope | undefined;
233
269
  readonly tracking: readonly (keyof Fs & string)[];
270
+ readonly backdate: BackdateSpec<keyof Fs & string> | undefined;
271
+ readonly hierarchy: HierarchySpec<keyof Fs & string> | undefined;
272
+ readonly delegates: readonly (keyof Fs & string)[];
273
+ readonly history: boolean;
234
274
  readonly indexes: readonly ResolvedIndex<keyof Fs & string>[];
235
275
  readonly sqlConstraints: readonly ResolvedSqlConstraint<keyof Fs & string>[];
236
276
  readonly constraints: readonly ResolvedConstraint[];