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,468 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import type { AuditRowInput } from '../../audit/index.js';
3
+ import { type Driver, type DriverConnection, type DriverQuery, type Row } from '../../driver-pg/index.js';
4
+ import type { KeyRing, Perm, RulePerm } from '../../security/index.js';
5
+ import { type EnqueueOptions } from '../events/events.js';
6
+ import { type DeliveredEvent, type RunningJob, type Worker } from '../events/workers.js';
7
+ import type { Id } from '../model/id.js';
8
+ import { type Fx } from '../money/fx.js';
9
+ import { type RecordCache } from '../recordset/recordset.js';
10
+ import type { ListLoaded, ModelName, ModelRef, RecordSet } from '../recordset/types.js';
11
+ import type { Registry } from '../registry/registry.js';
12
+ import { type RuntimeSecurity } from '../security/runtime.js';
13
+ import { type Identity, type ResolvedIdentity } from './identity.js';
14
+ import type { Inspector } from './inspector.js';
15
+ /** Typed context flags (RFC 0003 §7.4). Module-contributed flags arrive with the registry's second half. */
16
+ export interface Flags {
17
+ /** Searches hide archived records. Default `true`. */
18
+ readonly activeTest: boolean;
19
+ /** Audit / tracking messages are written. Default `true` (imports may turn it off). */
20
+ readonly tracking: boolean;
21
+ /** Multi-company consistency checks and scoping. Default `true`; only a superuser environment may disable it. */
22
+ readonly checkCompany: boolean;
23
+ }
24
+ /** A function registered with {@link Env.afterCommit} or {@link Env.onRollback}. */
25
+ export type Hook = () => void | Promise<void>;
26
+ /** Options of {@link Shutro.run}: the identity plus per-run transaction settings. */
27
+ export interface RunOptions extends Identity {
28
+ /** `BEGIN … READ ONLY`. Reports and replica-safe work. */
29
+ readonly readOnly?: boolean;
30
+ /** `false` disables automatic retries, e.g. for handlers that stream a response (RFC 0003 Q1). */
31
+ readonly retry?: false;
32
+ }
33
+ /** Query statistics of the current attempt. */
34
+ export interface ScopeStats {
35
+ readonly queries: number;
36
+ }
37
+ /** An undo record for savepoint rollback (RFC 0004 §7.6). */
38
+ export type JournalEntry = {
39
+ readonly kind: 'value';
40
+ readonly model: string;
41
+ readonly id: number;
42
+ readonly key: string;
43
+ readonly had: boolean;
44
+ readonly prev: unknown;
45
+ readonly wasDirty: boolean;
46
+ } | {
47
+ readonly kind: 'created';
48
+ readonly model: string;
49
+ readonly id: number;
50
+ } | {
51
+ readonly kind: 'deleted';
52
+ readonly model: string;
53
+ readonly id: number;
54
+ readonly values: Map<string, unknown>;
55
+ readonly dirty: Set<string> | undefined;
56
+ };
57
+ /** A transaction or savepoint. */
58
+ interface Scope {
59
+ readonly root: RootScope;
60
+ readonly parent: Scope | undefined;
61
+ readonly conn: DriverConnection;
62
+ status: 'open' | 'committed' | 'rolled-back';
63
+ env: Env;
64
+ readonly afterCommit: Hook[];
65
+ readonly onRollback: Hook[];
66
+ /** Cache changes made in this savepoint, for undo; `undefined` for the root transaction. */
67
+ readonly journal: JournalEntry[] | undefined;
68
+ }
69
+ interface RootScope {
70
+ /** The innermost open scope: the only one whose env may run statements. */
71
+ top: Scope;
72
+ readonly attempt: number;
73
+ readonly now: Date;
74
+ queries: number;
75
+ /** Identity map and value-object caches (RFC 0004 §7.4), shared by the savepoints of this attempt. */
76
+ readonly cache: RecordCache;
77
+ /** Unit of work: model → id → dirty field keys. */
78
+ readonly dirty: Map<string, Map<number, Set<string>>>;
79
+ /** Raw compute triggers: model → key → changed ids (RFC 0008 §7.2). */
80
+ readonly triggers: Map<string, Map<string, Set<number>>>;
81
+ /** Records marked for computation directly (new records): model → key → ids. */
82
+ readonly toCompute: Map<string, Map<string, Set<number>>>;
83
+ /** Records to check: model → constraint key → ids (RFC 0009 §7.1). */
84
+ readonly toCheck: Map<string, Map<string, Set<number>>>;
85
+ readonly compute: ComputeState;
86
+ /** Pending audit rows of this attempt (RFC 0013 §7.2). */
87
+ readonly audit: AuditRowInput[];
88
+ /** Groups the audit rows of this attempt. */
89
+ readonly tx: string;
90
+ /** Next virtual id for drafts (negative, RFC 0009 §7.4). */
91
+ virtual: number;
92
+ readonly uid: number;
93
+ /** Set in `env.asOf` scopes: reads see the models with history as they were then; writes are refused. */
94
+ readonly asOf?: Date;
95
+ }
96
+ /** Compute-engine state of an attempt (RFC 0008 §7.3, §7.5). */
97
+ export interface ComputeState {
98
+ recomputing: boolean;
99
+ /** `model.key` names being computed right now (assignment is allowed for them). */
100
+ readonly computing: Set<string>;
101
+ /** `model.key` → ids computed in the current round: invalidation and re-triggering skip them. */
102
+ readonly protected: Map<string, Set<number>>;
103
+ /** `model.key` → id → the value invalidated by a trigger, for the audit row of the recompute (RFC 0013). */
104
+ readonly previous: Map<string, Map<number, unknown>>;
105
+ }
106
+ interface Runtime {
107
+ readonly als: AsyncLocalStorage<Scope>;
108
+ readonly onHookError: (error: unknown, phase: 'afterCommit' | 'onRollback') => void;
109
+ readonly registry: Registry | undefined;
110
+ /** Dev-mode query inspector, if any. */
111
+ readonly inspector: Inspector | undefined;
112
+ /** The pool, for autonomous transactions (standard sequences, RFC 0012 §7.2). */
113
+ readonly driver: Driver;
114
+ /** Encryption keys for `encrypted` fields (RFC 0014 §7.6), or none. */
115
+ readonly keys: KeyRing | undefined;
116
+ /** The language translations fall back to (RFC 0011). */
117
+ readonly sourceLang: string;
118
+ /** Runtime security (RFC 0014 §7.10): the loaded overlay, when enabled. */
119
+ readonly security: {
120
+ enabled: boolean;
121
+ current: RuntimeSecurity | undefined;
122
+ loading: Promise<void> | undefined;
123
+ };
124
+ }
125
+ /** @internal What the recordset runtime needs from an environment. */
126
+ export interface ScopeInternals {
127
+ readonly env: Env;
128
+ readonly registry: Registry;
129
+ /** Runtime security additions (RFC 0014 §7.10), when enabled. */
130
+ readonly overlay: RuntimeSecurity | undefined;
131
+ /** The instant of an `env.asOf` scope (RFC 0018 §7.4). */
132
+ readonly asOf: Date | undefined;
133
+ readonly cache: RecordCache;
134
+ readonly uid: number;
135
+ readonly now: Date;
136
+ query<R extends Row>(query: DriverQuery): Promise<readonly R[]>;
137
+ /** `COPY ... FROM STDIN` on the scope's connection (RFC 0015 §7.1); returns the row count. */
138
+ copyIn(query: DriverQuery, lines: Iterable<string>): Promise<number>;
139
+ /** Records an undo entry when a savepoint is active. */
140
+ journal(entry: JournalEntry): void;
141
+ markDirty(model: string, id: number, key: string): void;
142
+ isDirty(model: string, id: number, key: string): boolean;
143
+ dirtyFields(model: string, id: number): Set<string> | undefined;
144
+ dirtyModels(): string[];
145
+ /** Removes and returns the dirty map of a model. */
146
+ takeDirty(model: string): Map<number, Set<string>> | undefined;
147
+ /** Drops a record from the cache and the unit of work. */
148
+ forget(model: string, id: number): void;
149
+ cachedValues(model: string): Iterable<Map<string, unknown>>;
150
+ readonly sourceLang: string;
151
+ readonly driver: Driver;
152
+ readonly keys: KeyRing | undefined;
153
+ /** Pending audit rows (RFC 0013 §7.2). */
154
+ readonly auditRows: AuditRowInput[];
155
+ readonly tx: string;
156
+ flush(model?: string): Promise<void>;
157
+ /** Records that `(model, key)` changed for `ids` and invalidates cached dependents (RFC 0008 §7.2). */
158
+ trigger(model: string, key: string, ids: readonly number[]): void;
159
+ /** Marks `ids` for computation of the stored computed field `key` (new records). */
160
+ markToCompute(model: string, key: string, ids: readonly number[]): void;
161
+ takeTriggers(): Map<string, Map<string, Set<number>>>;
162
+ takeToCompute(): Map<string, Map<string, Set<number>>>;
163
+ hasPending(): boolean;
164
+ takeToCheck(): Map<string, Map<string, Set<number>>>;
165
+ hasChecks(): boolean;
166
+ /** A fresh negative id for a draft record (RFC 0009 §7.4). */
167
+ nextVirtualId(): number;
168
+ readonly compute: ComputeState;
169
+ }
170
+ /** @internal */
171
+ export declare function internalsOf(env: Env): ScopeInternals;
172
+ /**
173
+ * The environment (RFC 0003): who is acting, for which company, how, and in which transaction. Immutable; the
174
+ * `with*` methods return derived environments that share the transaction scope. `S` is the schema view of the
175
+ * registry (model name → model), which types `model()`.
176
+ */
177
+ export declare class Env<S = unknown> {
178
+ #private;
179
+ /** Id of the acting user. */
180
+ readonly uid: number;
181
+ /** Current company id. */
182
+ readonly companyId: number;
183
+ /** Allowed company ids (record-rule scope). */
184
+ readonly companyIds: readonly number[];
185
+ readonly lang: string;
186
+ /** {@link uid} as a `res.users` id, for many2one defaults: `default: (env) => env.userId`. */
187
+ get userId(): Id<'res.users'>;
188
+ /** {@link companyId} as a `res.company` id. */
189
+ get companyRef(): Id<'res.company'>;
190
+ /** The language translatable fields fall back to when `lang` has no text (RFC 0011). */
191
+ readonly sourceLang: string;
192
+ readonly tz: string;
193
+ /** Superuser mode: only inside {@link asSuperuser}. */
194
+ readonly su: boolean;
195
+ /**
196
+ * The user is in an administrator group (`defineGroup({ administrator: true })`): every ACL, record rule, field
197
+ * group and permission passes, without grants (RFC 0014 §7.9). Company scoping still applies.
198
+ */
199
+ readonly administrator: boolean;
200
+ /** Reason for a job or superuser scope, when given. */
201
+ readonly reason: string | undefined;
202
+ /** The user's security groups, closed over `implies` (RFC 0014 §7.1). */
203
+ readonly groups: ReadonlySet<string>;
204
+ /** Special permissions of this user on top of the roles (`'account.backdate'`, `'account.move:unlink'`). */
205
+ readonly grants: ReadonlySet<string>;
206
+ /** @internal Encryption keys. */
207
+ readonly keys: KeyRing | undefined;
208
+ readonly flags: Flags;
209
+ /** 1 for the first attempt of `run()`, 2+ for retries after a serialization failure or deadlock. */
210
+ readonly attempt: number;
211
+ readonly readOnly: boolean;
212
+ /** @internal */
213
+ constructor(identity: ResolvedIdentity & {
214
+ readonly su: boolean;
215
+ readonly flags: Flags;
216
+ readonly readOnly: boolean;
217
+ }, scope: Scope, runtime: Runtime);
218
+ /** An empty recordset of `name`: `search()` / `browse()` / `create()` start here (RFC 0004). */
219
+ model<M extends ModelName<S>>(name: M): ModelRef<S, M>;
220
+ /** What this environment may do (RFC 0014): for Kosh menus, export / import buttons and API guards. */
221
+ get access(): {
222
+ can(model: ModelName<S>, perm: Perm): boolean;
223
+ /** @throws {AccessError} */
224
+ check(model: ModelName<S>, perm: Perm): void;
225
+ /**
226
+ * Checks model access and the record rules of `perm` for these ids without changing anything: may this user write
227
+ * (or unlink) these records? @throws {AccessError} out of scope, {@link MissingRecordError} for unknown ids
228
+ */
229
+ checkRecords(model: ModelName<S>, ids: readonly number[], perm: RulePerm): Promise<void>;
230
+ canField(model: ModelName<S>, field: string, kind: 'read' | 'write'): boolean;
231
+ /** The feature permission `code` (`definePermission`): granted by a group, or administrator. */
232
+ has(code: string): boolean;
233
+ /** @throws {AccessError} unless {@link has}. */
234
+ require(code: string): void;
235
+ /**
236
+ * The group and role codes that make their holder an administrator (an administrator group, or implying one),
237
+ * from code and runtime roles: what sign-in, 2FA policy and "keep one administrator" checks look for.
238
+ */
239
+ administratorGroups(): ReadonlySet<string>;
240
+ };
241
+ /**
242
+ * The record with external id `id` (`'base.main_company'`, RFC 0017), nothing loaded.
243
+ * @throws {UnknownExternalIdError} for an unknown id or a record of another model.
244
+ */
245
+ ref<M extends ModelName<S>>(model: M, id: string): Promise<RecordSet<S, M, ListLoaded<never>>>;
246
+ /** The id of the record with external id `id`. @throws {UnknownExternalIdError} */
247
+ refId<M extends ModelName<S>>(model: M, id: string): Promise<Id<M>>;
248
+ /**
249
+ * Runtime security administration (RFC 0014 §7.10): roles, model access, record rules and permission grants, on top
250
+ * of the code's declarations. Administrators (or superuser scopes) only; each change is validated against the
251
+ * registry, audited, and reloaded by every process once committed. Needs `createShutro({ runtimeSecurity: true })`.
252
+ */
253
+ get securityAdmin(): SecurityAdmin;
254
+ /**
255
+ * Emits a domain event in this transaction (RFC 0018 §7.2): it exists if and only if the transaction commits, and
256
+ * subscribers (`shutro.subscribe`) receive it at least once. Returns the event id.
257
+ */
258
+ emit(topic: string, payload: unknown): Promise<number>;
259
+ /**
260
+ * Enqueues a background job in this transaction (RFC 0018 §7.3), run by `shutro.work` as this user, with
261
+ * retries. With `key`, a job already pending or running under that key makes this a no-op (returns `null`).
262
+ */
263
+ enqueue(name: string, payload: unknown, options?: EnqueueOptions): Promise<number | null>;
264
+ /** Dated, per-company currency conversion (RFC 0006 §7.6). Needs a `res.currency.rate` model. */
265
+ get fx(): Fx;
266
+ /** The transaction timestamp (PostgreSQL `now()`), stable within an attempt. Returns a fresh `Date` each call. */
267
+ now(): Date;
268
+ /** Today's calendar date (`'YYYY-MM-DD'`) in the environment's time zone. */
269
+ today(): string;
270
+ /** Today's calendar date in another time zone. */
271
+ todayIn(tz: string): string;
272
+ /** Writes every pending change of the unit of work to the database now (RFC 0004 §7.6). */
273
+ flush(): Promise<void>;
274
+ /** Statistics of the current attempt (query counts for N+1 assertions, RFC 0004 §7.9). */
275
+ stats(): ScopeStats;
276
+ /**
277
+ * Raw SQL in this transaction (RFC 0005 §7.8): values become parameters, identifiers go through `sql.id()`.
278
+ * Pending writes are flushed first. Rejects with {@link TransactionScopeError} when the scope has ended or
279
+ * another scope is active.
280
+ */
281
+ sql<R extends Row = Row>(strings: TemplateStringsArray, ...values: readonly unknown[]): Promise<readonly R[]>;
282
+ /**
283
+ * Runs `fn` in a savepoint: its database work and its cache changes are undone if it throws, kept otherwise.
284
+ * Pending writes are flushed before the savepoint is released.
285
+ */
286
+ transaction<T>(fn: (env: Env<S>) => Promise<T>): Promise<T>;
287
+ /** Registers work to run only after the outermost transaction commits (emails, webhooks, queue messages). */
288
+ afterCommit(hook: Hook): void;
289
+ /** Registers work to run if this scope rolls back (cleanup of external resources). */
290
+ onRollback(hook: Hook): void;
291
+ /** The same scope with another current company. Must be allowed unless `su`. @throws {CompanyNotAllowedError} */
292
+ withCompany(company: number): Env<S>;
293
+ /**
294
+ * Drops clean records from this scope's cache (all models, or one): for long reads in one transaction, such as
295
+ * streaming an export of millions of rows page by page, so memory stays bounded. Records with unsaved changes or
296
+ * pending computes and checks are kept; dropped records are simply loaded again when read.
297
+ */
298
+ releaseCache(model?: string): void;
299
+ /** The same scope with another language. */
300
+ withLang(lang: string): Env<S>;
301
+ /** The same scope with another time zone. */
302
+ withTz(tz: string): Env<S>;
303
+ /** The same scope with some flags changed. `checkCompany: false` needs `su`. @throws {FlagNotAllowedError} */
304
+ withFlags(flags: Partial<Flags>): Env<S>;
305
+ /**
306
+ * Runs `fn` reading the past (RFC 0018 §7.4): models with `history: true` are searched and loaded as they were at
307
+ * `instant` (rules, field groups and company scope apply as now); other models are read as they are now. The
308
+ * environment has its own cache and is read-only: writes are refused.
309
+ *
310
+ * ```ts
311
+ * const atClose = await env.asOf(new Date('2026-09-30T23:59:59Z'), (past) => past.model('account.move').search({ where: { state: 'posted' } }).then((m) => m.read(['name', 'amountTotal'])));
312
+ * ```
313
+ */
314
+ asOf<T>(instant: Date, fn: (past: Env<S>) => Promise<T>): Promise<T>;
315
+ /**
316
+ * Runs `fn` with extra special grants in the same scope (RFC 0014 §7.9): a narrow, audited alternative to
317
+ * {@link asSuperuser} for code that must touch a model or feature its caller cannot. Record rules, field groups
318
+ * and company scoping still apply; only the named grants are added, and only inside `fn`.
319
+ *
320
+ * ```ts
321
+ * await env.withGrants({ grants: ['sale.order.line:read'], reason: 'invoice from orders' }, (e) => ...);
322
+ * ```
323
+ */
324
+ withGrants<T>(options: {
325
+ readonly grants: readonly string[];
326
+ readonly reason: string;
327
+ }, fn: (env: Env<S>) => Promise<T>): Promise<T>;
328
+ /**
329
+ * Runs `fn` with a superuser environment in the same scope. The elevation never leaks: only `su` and values
330
+ * returned by `fn` leave the callback, and `reason` is recorded for the audit trail (RFC 0003 §7.6).
331
+ */
332
+ asSuperuser<T>(options: {
333
+ readonly reason: string;
334
+ }, fn: (su: Env<S>) => Promise<T>): Promise<T>;
335
+ }
336
+ /** Options of {@link createShutro}. */
337
+ export interface ShutroOptions<S> {
338
+ readonly driver: Driver;
339
+ /** The registry built from the application's modules. Without it, `env.model()` is unavailable. */
340
+ readonly registry?: Registry<S>;
341
+ /** The source language of translatable fields: what readers of a language without text see. Default `en_US`. */
342
+ readonly sourceLang?: string;
343
+ /** Keys for `encrypted` fields (RFC 0014 §7.6): `createKeyRing({ current, keys })`. */
344
+ readonly keys?: KeyRing;
345
+ /** Dev-mode query inspector (`createInspector()`): SQL, timings, N+1 warnings. */
346
+ readonly inspector?: Inspector;
347
+ /**
348
+ * Verifies identities against the application's data (RFC 0014 §7.1, docs/feedback.md #6): returns the user's
349
+ * allowed companies and groups, or `null` for an unknown or disabled user. When set, `run()` refuses companies
350
+ * outside the allowed set and groups the user does not have, and uses the loaded groups when none are given.
351
+ */
352
+ readonly identity?: (uid: number) => Promise<VerifiedIdentity | null>;
353
+ /**
354
+ * Roles, access, record rules and permission grants edited at runtime (RFC 0014 §7.10), on top of the code's
355
+ * declarations. Loaded at the first run and reloaded whenever a change is committed (by any process).
356
+ */
357
+ readonly runtimeSecurity?: boolean;
358
+ /** Retry policy for serialization failures and deadlocks. Default: 5 attempts with jittered exponential backoff. */
359
+ readonly retry?: {
360
+ readonly attempts?: number;
361
+ /** Delay before attempt `attempt` (2+), in milliseconds. */
362
+ readonly backoffMs?: (attempt: number) => number;
363
+ };
364
+ /**
365
+ * Called when an `afterCommit` / `onRollback` hook throws (the transaction outcome is already decided, so the
366
+ * error cannot be surfaced to the caller). Defaults to `process.emitWarning`.
367
+ */
368
+ readonly onHookError?: (error: unknown, phase: 'afterCommit' | 'onRollback') => void;
369
+ }
370
+ /** Options of {@link Shutro.bootstrap}. */
371
+ export interface BootstrapOptions {
372
+ /** Why the system acts (audited), e.g. `'install'`. */
373
+ readonly reason: string;
374
+ /** Current company, once one exists; company-scoped defaults and sequences use it. */
375
+ readonly company?: number;
376
+ }
377
+ /** `env.securityAdmin` (RFC 0014 §7.10). */
378
+ export interface SecurityAdmin {
379
+ /** Creates or updates a runtime role. */
380
+ saveRole(role: {
381
+ readonly code: string;
382
+ readonly label?: string;
383
+ readonly implies?: readonly string[];
384
+ readonly administrator?: boolean;
385
+ }): Promise<void>;
386
+ /** Deletes a runtime role with its access, rules and grants. */
387
+ deleteRole(code: string): Promise<void>;
388
+ /** Sets what `role` may do on `model` (an empty list removes the runtime grant; code grants stay). */
389
+ setAccess(role: string, model: string, perms: readonly Perm[]): Promise<void>;
390
+ /** Creates or updates a record rule for `role` (the domain is compiled when saved). */
391
+ saveRule(rule: {
392
+ readonly name: string;
393
+ readonly role: string;
394
+ readonly model: string;
395
+ readonly perms: readonly RulePerm[];
396
+ readonly domain: Readonly<Record<string, unknown>>;
397
+ }): Promise<void>;
398
+ deleteRule(name: string): Promise<void>;
399
+ /** Grants a feature permission (declared by a module) to `role`. */
400
+ grantPermission(role: string, permission: string): Promise<void>;
401
+ revokePermission(role: string, permission: string): Promise<void>;
402
+ /**
403
+ * Field security at runtime: the roles that may read / write `model.field`, on top of its code groups (writers can
404
+ * read). A field without code groups becomes restricted to these roles; empty lists remove the runtime entry.
405
+ */
406
+ setFieldGroups(model: string, field: string, groups: {
407
+ readonly read?: readonly string[];
408
+ readonly write?: readonly string[];
409
+ }): Promise<void>;
410
+ }
411
+ /** What an identity loader returns for a user. */
412
+ export interface VerifiedIdentity {
413
+ readonly companies: readonly number[];
414
+ readonly groups: readonly string[];
415
+ /** The user's special permissions (see `Identity.grants`). */
416
+ readonly grants?: readonly string[];
417
+ }
418
+ /** A Shutro instance: one driver, one registry, one AsyncLocalStorage. No global state (`CLAUDE.md`). */
419
+ export interface Shutro<S = unknown> {
420
+ /**
421
+ * Runs `fn` in one transaction with the given identity (RFC 0003 §7.1): `REPEATABLE READ`, identity pushed as
422
+ * `SET LOCAL` settings (`shutro.user_id`, `shutro.company_ids`), `TimeZone = UTC`. Pending writes are flushed
423
+ * before commit. Commits when `fn` resolves, rolls back when it throws. Serialization failures and deadlocks
424
+ * re-run `fn` from scratch with a fresh scope (so `fn` must have no side effects outside the database; use
425
+ * `env.afterCommit`).
426
+ *
427
+ * @throws {InvalidIdentityError} before any transaction starts.
428
+ * @throws {ConcurrentUpdateError} when every attempt conflicted.
429
+ */
430
+ run<T>(options: RunOptions, fn: (env: Env<S>) => Promise<T>): Promise<T>;
431
+ /**
432
+ * Runs `fn` as the system (uid {@link SYSTEM_UID}) in a superuser scope, for installing a database before any
433
+ * user exists (feedback #5): `created_by` / `updated_by` are written as `NULL`, the scope is audited with
434
+ * `reason`, and the identity loader is not consulted. Pass `company` once the first company exists, so
435
+ * company-scoped defaults have a value.
436
+ *
437
+ * ```ts
438
+ * await shutro.bootstrap({ reason: 'install' }, async (env) => {
439
+ * const [company] = await env.model('res.company').create([{ name: 'Acme', currency: bdt }]);
440
+ * await env.model('res.users').create([{ login: 'admin', name: 'Administrator' }]);
441
+ * });
442
+ * ```
443
+ */
444
+ bootstrap<T>(options: BootstrapOptions, fn: (env: Env<S>) => Promise<T>): Promise<T>;
445
+ /** The environment of the innermost active scope. @throws {NoEnvironmentError} outside `run()`. */
446
+ currentEnv(): Env<S>;
447
+ /** The registry this instance was created with. */
448
+ readonly registry: Registry | undefined;
449
+ /** The driver this instance was created with. */
450
+ readonly driver: Driver;
451
+ /** Reloads runtime security now (changes are also reloaded automatically after they commit). */
452
+ reloadSecurity(): Promise<void>;
453
+ /**
454
+ * A subscriber of `topic` named `name` (RFC 0018 §7.2): events in order, at least once, the cursor advancing in the
455
+ * handler's transaction. One delivery at a time per name, across processes.
456
+ */
457
+ subscribe(name: string, topic: string, handler: (event: DeliveredEvent, env: Env<S>) => Promise<void>, options?: {
458
+ readonly attempts?: number;
459
+ readonly pollMs?: number;
460
+ }): Worker;
461
+ /** A job worker for these job names (RFC 0018 §7.3); start any number, in any processes. */
462
+ work(handlers: Readonly<Record<string, (payload: unknown, env: Env<S>, job: RunningJob) => Promise<void>>>, options?: {
463
+ readonly pollMs?: number;
464
+ }): Worker;
465
+ }
466
+ /** Creates a {@link Shutro} instance on a driver (and a registry). */
467
+ export declare function createShutro<S = unknown>(options: ShutroOptions<S>): Shutro<S>;
468
+ export {};