@happyvertical/smrt-tenancy 0.47.2 → 0.49.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.
- package/AGENTS.md +13 -1
- package/dist/chunks/{testing-Cow9qCBw.js → testing-CrMnRY8M.js} +101 -24
- package/dist/chunks/testing-CrMnRY8M.js.map +1 -0
- package/dist/decorators.d.ts.map +1 -1
- package/dist/index.js +15 -7
- package/dist/index.js.map +1 -1
- package/dist/interceptor.d.ts.map +1 -1
- package/dist/manifest.json +1 -1
- package/dist/registry.d.ts +18 -8
- package/dist/registry.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +5 -5
- package/dist/testing.js +1 -1
- package/package.json +5 -5
- package/dist/chunks/testing-Cow9qCBw.js.map +0 -1
package/AGENTS.md
CHANGED
|
@@ -81,6 +81,17 @@ class Doc extends SmrtObject { @tenantId({ nullable: true }) tenantId: string |
|
|
|
81
81
|
class Doc extends SmrtObject { tenantId: string | null = null; }
|
|
82
82
|
```
|
|
83
83
|
|
|
84
|
+
The exported `registerTenantScopedClass()` also accepts a simple or qualified
|
|
85
|
+
string selector for third-party classes and test doubles. A simple selector is
|
|
86
|
+
bound to the one exact core constructor when that name is uniquely resolvable;
|
|
87
|
+
it may be registered before core. Once bound, a later same-name package peer
|
|
88
|
+
does not inherit its policy. If two core classes exist before the simple
|
|
89
|
+
selector can bind, operations fail closed until the caller registers an exact
|
|
90
|
+
qualified name (for example, `@package/name:Doc`). No lookup strips a namespace
|
|
91
|
+
to guess an owner. If core clears a bound constructor and reuses its qualified
|
|
92
|
+
name, unregister and register the selector again; it will not silently transfer
|
|
93
|
+
policy to the replacement constructor.
|
|
94
|
+
|
|
84
95
|
Modes: `'required'` (default — throws without context) or `'optional'` (passes through if no context).
|
|
85
96
|
|
|
86
97
|
## Adapters
|
|
@@ -100,7 +111,8 @@ Modes: `'required'` (default — throws without context) or `'optional'` (passes
|
|
|
100
111
|
- **Auto-populate only if empty**: if tenantId already set, interceptor validates (not overwrites)
|
|
101
112
|
- **Isolation checked at query time**: `list({ where: { tenantId: 'other' } })` throws immediately
|
|
102
113
|
- **Testing**: `resetTenancy()` + `setupTestTenancy()` in beforeEach; `testTenantIsolation()` helper
|
|
103
|
-
- **Natural keys are per tenant (smrt#2360)**: a tenant-scoped class with no explicit `conflictColumns` upserts on, and indexes, `(tenant_id, slug, context[, _meta_type])` — `save()` from tenant B with tenant A's slug is a second row, never an overwrite; within a tenant the natural key still dedups; NULL-tenant (`optional` mode, no context) rows dedup among themselves through the SDK's null-aware upsert but not through the index (NULLs are distinct), so raw SQL `ON CONFLICT (slug, context…)` on such a table no longer binds — use `WHERE NOT EXISTS`, and on PostgreSQL an advisory lock, as `ProfileTypeCollection.getOrCreateGlobalBySlug()` does. Core
|
|
114
|
+
- **Natural keys are per tenant (smrt#2360)**: a tenant-scoped class with no explicit `conflictColumns` upserts on, and indexes, `(tenant_id, slug, context[, _meta_type])` — `save()` from tenant B with tenant A's slug is a second row, never an overwrite; within a tenant the natural key still dedups; NULL-tenant (`optional` mode, no context) rows dedup among themselves through the SDK's null-aware upsert but not through the index (NULLs are distinct), so raw SQL `ON CONFLICT (slug, context…)` on such a table no longer binds — use `WHERE NOT EXISTS`, and on PostgreSQL an advisory lock, as `ProfileTypeCollection.getOrCreateGlobalBySlug()` does. Core resolves tenant schema policy in order: explicit `@smrt`, manifest (including an omitted `tenantScoped`), exact-constructor `@TenantScoped()` reconciliation, then marked-field fallback; it never reads the standalone tenancy registry. This keeps schema and upsert behavior aligned before `enableTenancy()` runs. Rollout: deploy the code and `smrt db:migrate` together (neither version's create works against the other's index), and backfill `tenant_id` on legacy NULL-tenant rows first — a tenant-context save no longer adopts a `(NULL, slug)` row, it inserts beside it and that tenant stops seeing the legacy one (details in `packages/core/agents/schema-paths.md`).
|
|
115
|
+
- **Manifest/runtime mismatch fails closed (smrt#2763)**: if a cached manifest omits or sets `tenantScoped: false` while the exact runtime constructor carries `@TenantScoped()`, registration is rejected; regenerate the manifest. A rejected late manifest or conflicting promotion preserves a previously valid scoped registration. Applying `@TenantScoped()` to an already-global manifest registration that omits or disables tenancy instead marks that class unavailable to conflict-key, schema, and tenancy interceptor operations until a corrected manifest explicitly declares tenancy. This prevents a global unique key from conflicting with tenant-enforced reads or writes.
|
|
104
116
|
|
|
105
117
|
## Known exceptions to monorepo standards
|
|
106
118
|
|
|
@@ -10,25 +10,92 @@ var DEFAULT_CONFIG = {
|
|
|
10
10
|
allowSuperAdminBypass: false
|
|
11
11
|
};
|
|
12
12
|
var tenantScopedClasses = /* @__PURE__ */ new Map();
|
|
13
|
+
var directSimpleRegistrations = /* @__PURE__ */ new Map();
|
|
14
|
+
var directQualifiedRegistrations = /* @__PURE__ */ new Map();
|
|
15
|
+
var directSimpleBindings = /* @__PURE__ */ new Map();
|
|
16
|
+
var unregisteredDecoratorRegistrations = /* @__PURE__ */ new Map();
|
|
17
|
+
function isQualifiedClassName(className) {
|
|
18
|
+
return className.includes(":");
|
|
19
|
+
}
|
|
20
|
+
function isCurrentDirectSimpleBinding(binding) {
|
|
21
|
+
return ObjectRegistry.getClassByQualifiedName(binding.qualifiedName)?.constructor === binding.constructor;
|
|
22
|
+
}
|
|
23
|
+
function bindDirectSimpleRegistration(className) {
|
|
24
|
+
if (!directSimpleRegistrations.get(className) || directSimpleBindings.has(className)) return;
|
|
25
|
+
const matches = ObjectRegistry.findClassesByName(className);
|
|
26
|
+
if (matches.length !== 1 || !matches[0].qualifiedName) return;
|
|
27
|
+
directSimpleBindings.set(className, {
|
|
28
|
+
qualifiedName: matches[0].qualifiedName,
|
|
29
|
+
constructor: matches[0].constructor
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
function getDirectSimpleRegistration(className) {
|
|
33
|
+
const config = directSimpleRegistrations.get(className);
|
|
34
|
+
if (!config) return void 0;
|
|
35
|
+
const binding = directSimpleBindings.get(className);
|
|
36
|
+
if (binding && !isCurrentDirectSimpleBinding(binding)) throw new Error(`Stale tenant-scoped class registration '${className}'; unregister and register it again for the current constructor.`);
|
|
37
|
+
if (ObjectRegistry.findClassesByName(className).length > 1) throw new Error(`Ambiguous tenant-scoped class registration '${className}'; register an explicit qualified class name instead.`);
|
|
38
|
+
return config;
|
|
39
|
+
}
|
|
40
|
+
function registerTenantScopedConstructor(target, config = {}) {
|
|
41
|
+
const resolved = {
|
|
42
|
+
...DEFAULT_CONFIG,
|
|
43
|
+
...config
|
|
44
|
+
};
|
|
45
|
+
unregisteredDecoratorRegistrations.set(target.name, resolved);
|
|
46
|
+
tenantScopedClasses.set(target.name, resolved);
|
|
47
|
+
}
|
|
13
48
|
function registerTenantScopedClass(className, config = {}) {
|
|
14
|
-
|
|
49
|
+
const resolved = {
|
|
15
50
|
...DEFAULT_CONFIG,
|
|
16
51
|
...config
|
|
17
|
-
}
|
|
52
|
+
};
|
|
53
|
+
tenantScopedClasses.set(className, resolved);
|
|
54
|
+
if (isQualifiedClassName(className)) {
|
|
55
|
+
directQualifiedRegistrations.set(className, resolved);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
directSimpleRegistrations.set(className, resolved);
|
|
59
|
+
const existingBinding = directSimpleBindings.get(className);
|
|
60
|
+
if (existingBinding && !isCurrentDirectSimpleBinding(existingBinding)) directSimpleBindings.delete(className);
|
|
61
|
+
bindDirectSimpleRegistration(className);
|
|
18
62
|
}
|
|
19
63
|
function unregisterTenantScopedClass(className) {
|
|
20
64
|
tenantScopedClasses.delete(className);
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
65
|
+
if (isQualifiedClassName(className)) {
|
|
66
|
+
directQualifiedRegistrations.delete(className);
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
directSimpleRegistrations.delete(className);
|
|
70
|
+
directSimpleBindings.delete(className);
|
|
71
|
+
unregisteredDecoratorRegistrations.delete(className);
|
|
25
72
|
}
|
|
26
73
|
function cloneConfig(config) {
|
|
27
74
|
return { ...config };
|
|
28
75
|
}
|
|
29
76
|
function getDirectTenantScopedConfig(className) {
|
|
30
|
-
|
|
31
|
-
|
|
77
|
+
ObjectRegistry.assertTenantScopedRegistrationValid(className);
|
|
78
|
+
const directQualified = directQualifiedRegistrations.get(className);
|
|
79
|
+
if (directQualified) return cloneConfig(directQualified);
|
|
80
|
+
const registered = isQualifiedClassName(className) ? ObjectRegistry.getClassByQualifiedName(className) : ObjectRegistry.getClass(className);
|
|
81
|
+
if (registered) {
|
|
82
|
+
const simple = registered.name;
|
|
83
|
+
const bound = directSimpleBindings.get(simple);
|
|
84
|
+
if (bound) {
|
|
85
|
+
if (bound.qualifiedName === className && bound.constructor === registered.constructor) return cloneConfig(directSimpleRegistrations.get(simple));
|
|
86
|
+
if (!isCurrentDirectSimpleBinding(bound)) throw new Error(`Stale tenant-scoped class registration '${simple}'; unregister and register it again for the current constructor.`);
|
|
87
|
+
}
|
|
88
|
+
if (!bound && directSimpleRegistrations.has(simple)) {
|
|
89
|
+
if (ObjectRegistry.findClassesByName(simple).length > 1) throw new Error(`Ambiguous tenant-scoped class registration '${simple}'; register an explicit qualified class name instead.`);
|
|
90
|
+
bindDirectSimpleRegistration(simple);
|
|
91
|
+
const rebound = directSimpleBindings.get(simple);
|
|
92
|
+
if (rebound?.qualifiedName === className && rebound.constructor === registered.constructor) return cloneConfig(directSimpleRegistrations.get(simple));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
if (!isQualifiedClassName(className)) {
|
|
96
|
+
const directSimple = getDirectSimpleRegistration(className);
|
|
97
|
+
if (directSimple) return cloneConfig(directSimple);
|
|
98
|
+
}
|
|
32
99
|
const coreConfig = ObjectRegistry.getTenantScopedConfig(className);
|
|
33
100
|
if (coreConfig) return {
|
|
34
101
|
mode: coreConfig.mode,
|
|
@@ -37,6 +104,10 @@ function getDirectTenantScopedConfig(className) {
|
|
|
37
104
|
autoPopulate: coreConfig.autoPopulate,
|
|
38
105
|
allowSuperAdminBypass: coreConfig.allowSuperAdminBypass
|
|
39
106
|
};
|
|
107
|
+
if (!registered && !isQualifiedClassName(className)) {
|
|
108
|
+
const decoratorConfig = unregisteredDecoratorRegistrations.get(className);
|
|
109
|
+
if (decoratorConfig) return cloneConfig(decoratorConfig);
|
|
110
|
+
}
|
|
40
111
|
}
|
|
41
112
|
function getInheritedTenantScopedConfig(className) {
|
|
42
113
|
const chain = ObjectRegistry.getInheritanceChain(className);
|
|
@@ -44,11 +115,6 @@ function getInheritedTenantScopedConfig(className) {
|
|
|
44
115
|
const ancestor = chain[i];
|
|
45
116
|
const direct = getDirectTenantScopedConfig(ancestor);
|
|
46
117
|
if (direct) return direct;
|
|
47
|
-
const simple = toSimpleClassName(ancestor);
|
|
48
|
-
if (simple !== ancestor) {
|
|
49
|
-
const bySimple = tenantScopedClasses.get(simple);
|
|
50
|
-
if (bySimple) return cloneConfig(bySimple);
|
|
51
|
-
}
|
|
52
118
|
}
|
|
53
119
|
}
|
|
54
120
|
function getTenantScopedConfig(className) {
|
|
@@ -64,6 +130,10 @@ function getAllTenantScopedClasses() {
|
|
|
64
130
|
}
|
|
65
131
|
function clearTenantScopedRegistry() {
|
|
66
132
|
tenantScopedClasses.clear();
|
|
133
|
+
directSimpleRegistrations.clear();
|
|
134
|
+
directQualifiedRegistrations.clear();
|
|
135
|
+
directSimpleBindings.clear();
|
|
136
|
+
unregisteredDecoratorRegistrations.clear();
|
|
67
137
|
}
|
|
68
138
|
//#endregion
|
|
69
139
|
//#region src/enabled-state.ts
|
|
@@ -89,6 +159,9 @@ async function runTenantScopedEntryPoint(options, fn) {
|
|
|
89
159
|
//#region src/interceptor.ts
|
|
90
160
|
var logger = createLogger({ level: "info" });
|
|
91
161
|
var DEFAULT_OPTIONS = { rawQueryPolicy: "throw" };
|
|
162
|
+
function getTenancyIdentity(className, context) {
|
|
163
|
+
return context.qualifiedClassName ?? className;
|
|
164
|
+
}
|
|
92
165
|
function serializeInstance(instance, className) {
|
|
93
166
|
const maybeToJSON = instance.toJSON;
|
|
94
167
|
if (typeof maybeToJSON === "function") return {
|
|
@@ -115,10 +188,11 @@ function createTenantInterceptor(options = {}) {
|
|
|
115
188
|
* Before list: Add tenant filter to queries
|
|
116
189
|
*/
|
|
117
190
|
beforeList(className, listOptions, context) {
|
|
118
|
-
|
|
191
|
+
const tenancyIdentity = getTenancyIdentity(className, context);
|
|
192
|
+
if (!isTenantScopedClass(tenancyIdentity)) return;
|
|
119
193
|
if (isSuperAdminBypass()) return;
|
|
120
194
|
if (isSystemContext()) return;
|
|
121
|
-
const config = getTenantScopedConfig(
|
|
195
|
+
const config = getTenantScopedConfig(tenancyIdentity);
|
|
122
196
|
const tenantContext = getCurrentTenant();
|
|
123
197
|
if (!tenantContext) {
|
|
124
198
|
if (config?.mode === "required") {
|
|
@@ -179,10 +253,11 @@ function createTenantInterceptor(options = {}) {
|
|
|
179
253
|
* Before get: Add tenant filter to single record fetches
|
|
180
254
|
*/
|
|
181
255
|
beforeGet(className, filter, context) {
|
|
182
|
-
|
|
256
|
+
const tenancyIdentity = getTenancyIdentity(className, context);
|
|
257
|
+
if (!isTenantScopedClass(tenancyIdentity)) return;
|
|
183
258
|
if (isSuperAdminBypass()) return;
|
|
184
259
|
if (isSystemContext()) return;
|
|
185
|
-
const config = getTenantScopedConfig(
|
|
260
|
+
const config = getTenantScopedConfig(tenancyIdentity);
|
|
186
261
|
const tenantContext = getCurrentTenant();
|
|
187
262
|
if (!tenantContext) {
|
|
188
263
|
if (config?.mode === "required") {
|
|
@@ -216,7 +291,7 @@ function createTenantInterceptor(options = {}) {
|
|
|
216
291
|
* Before query: Handle raw SQL on tenant-scoped classes
|
|
217
292
|
*/
|
|
218
293
|
beforeQuery(className, queryOptions, context) {
|
|
219
|
-
if (!isTenantScopedClass(className)) return;
|
|
294
|
+
if (!isTenantScopedClass(getTenancyIdentity(className, context))) return;
|
|
220
295
|
if (queryOptions.allowRawOnTenantScoped) {
|
|
221
296
|
opts.onRawQuery?.(className, queryOptions.sql, context);
|
|
222
297
|
return;
|
|
@@ -251,10 +326,11 @@ function createTenantInterceptor(options = {}) {
|
|
|
251
326
|
_directoryIsNew: id === void 0 || id === null
|
|
252
327
|
};
|
|
253
328
|
}
|
|
254
|
-
|
|
329
|
+
const tenancyIdentity = getTenancyIdentity(className, context);
|
|
330
|
+
if (!isTenantScopedClass(tenancyIdentity)) return;
|
|
255
331
|
if (isSuperAdminBypass()) return;
|
|
256
332
|
if (isSystemContext()) return;
|
|
257
|
-
const config = getTenantScopedConfig(
|
|
333
|
+
const config = getTenantScopedConfig(tenancyIdentity);
|
|
258
334
|
const tenantField = config?.field || "tenantId";
|
|
259
335
|
const instanceRecord = instance;
|
|
260
336
|
const instanceTenantId = instanceRecord[tenantField];
|
|
@@ -284,10 +360,11 @@ function createTenantInterceptor(options = {}) {
|
|
|
284
360
|
*/
|
|
285
361
|
beforeDelete(instance, context) {
|
|
286
362
|
const className = context.className;
|
|
287
|
-
|
|
363
|
+
const tenancyIdentity = getTenancyIdentity(className, context);
|
|
364
|
+
if (!isTenantScopedClass(tenancyIdentity)) return;
|
|
288
365
|
if (isSuperAdminBypass()) return;
|
|
289
366
|
if (isSystemContext()) return;
|
|
290
|
-
const config = getTenantScopedConfig(
|
|
367
|
+
const config = getTenantScopedConfig(tenancyIdentity);
|
|
291
368
|
const instanceTenantId = instance[config?.field || "tenantId"];
|
|
292
369
|
const tenantContext = getCurrentTenant();
|
|
293
370
|
if (!tenantContext) {
|
|
@@ -397,6 +474,6 @@ async function assertTenantIsolationViolation(fn, messageContains) {
|
|
|
397
474
|
}
|
|
398
475
|
}
|
|
399
476
|
//#endregion
|
|
400
|
-
export {
|
|
477
|
+
export { registerTenantScopedConstructor as _, setupTestTenancy as a, disableTenancy as c, isTenancyEnabled as d, clearTenantScopedRegistry as f, registerTenantScopedClass as g, isTenantScopedClass as h, resetTenancy as i, enableTenancy as l, getTenantScopedConfig as m, assertTenantIsolationViolation as n, testTenantIsolation as o, getAllTenantScopedClasses as p, createTestTenantContext as r, createTenantInterceptor as s, assertTenantContextRequired as t, runTenantScopedEntryPoint as u, unregisterTenantScopedClass as v };
|
|
401
478
|
|
|
402
|
-
//# sourceMappingURL=testing-
|
|
479
|
+
//# sourceMappingURL=testing-CrMnRY8M.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"testing-CrMnRY8M.js","names":[],"sources":["../../src/registry.ts","../../src/enabled-state.ts","../../src/entry-point.ts","../../src/interceptor.ts","../../src/testing.ts"],"sourcesContent":["/**\n * Tenant-Scoped Class Registry\n *\n * Tracks which classes are tenant-scoped and their configuration.\n * Used by the interceptor to determine how to handle operations.\n *\n * This registry supports two patterns:\n * 1. @TenantScoped() decorator + tenantId field (original pattern)\n * 2. @smrt({ tenantScoped: true }) in smrt-core (Issue #688 pattern)\n *\n * Both patterns are automatically recognized by the interceptor.\n *\n * @see https://github.com/happyvertical/smrt/issues/675\n * @see https://github.com/happyvertical/smrt/issues/688\n */\n\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\n/**\n * Resolved tenancy configuration for a single class, as stored in the registry.\n *\n * Every field has a concrete (non-optional) value — defaults are applied by\n * `registerTenantScopedClass()` when the class is registered via `@TenantScoped()`.\n *\n * @see TenantScopedOptions\n * @see registerTenantScopedClass\n */\nexport interface TenantScopedConfig {\n /**\n * Tenancy mode for this class\n * - 'required': Must have tenant context for all operations\n * - 'optional': Works with or without tenant context\n * @default 'required'\n */\n mode: 'required' | 'optional';\n\n /**\n * Field name containing tenant ID\n * @default 'tenantId'\n */\n field: string;\n\n /**\n * Auto-filter all queries by tenant\n * @default true\n */\n autoFilter: boolean;\n\n /**\n * Auto-populate tenant ID from context on create\n * @default true\n */\n autoPopulate: boolean;\n\n /**\n * Allow super admin bypass for this class\n * @default false\n */\n allowSuperAdminBypass: boolean;\n}\n\nconst DEFAULT_CONFIG: TenantScopedConfig = {\n mode: 'required',\n field: 'tenantId',\n autoFilter: true,\n autoPopulate: true,\n allowSuperAdminBypass: false,\n};\n\n// Registry snapshot exposed by getAllTenantScopedClasses().\nconst tenantScopedClasses = new Map<string, TenantScopedConfig>();\n\n// Direct callers select a class by string. Keep simple and qualified selectors\n// separate: a simple selector may be bound only after core proves that exactly\n// one constructor owns that name.\nconst directSimpleRegistrations = new Map<string, TenantScopedConfig>();\nconst directQualifiedRegistrations = new Map<string, TenantScopedConfig>();\nconst directSimpleBindings = new Map<\n string,\n { qualifiedName: string; constructor: Function }\n>();\n\n// Decorators retain a simple mirror only until core has registered their\n// authoritative qualified policy. Qualified runtime resolution always defers\n// to core, preserving manifest and explicit-@smrt precedence.\nconst unregisteredDecoratorRegistrations = new Map<\n string,\n TenantScopedConfig\n>();\n\nfunction isQualifiedClassName(className: string): boolean {\n return className.includes(':');\n}\n\nfunction isCurrentDirectSimpleBinding(binding: {\n qualifiedName: string;\n constructor: Function;\n}): boolean {\n return (\n ObjectRegistry.getClassByQualifiedName(binding.qualifiedName)\n ?.constructor === binding.constructor\n );\n}\n\nfunction bindDirectSimpleRegistration(className: string): void {\n const config = directSimpleRegistrations.get(className);\n if (!config || directSimpleBindings.has(className)) return;\n\n const matches = ObjectRegistry.findClassesByName(className);\n if (matches.length !== 1 || !matches[0].qualifiedName) return;\n\n directSimpleBindings.set(className, {\n qualifiedName: matches[0].qualifiedName,\n constructor: matches[0].constructor,\n });\n}\n\nfunction getDirectSimpleRegistration(\n className: string,\n): TenantScopedConfig | undefined {\n const config = directSimpleRegistrations.get(className);\n if (!config) return undefined;\n\n const binding = directSimpleBindings.get(className);\n if (binding && !isCurrentDirectSimpleBinding(binding)) {\n throw new Error(\n `Stale tenant-scoped class registration '${className}'; ` +\n 'unregister and register it again for the current constructor.',\n );\n }\n\n const matches = ObjectRegistry.findClassesByName(className);\n if (matches.length > 1) {\n throw new Error(\n `Ambiguous tenant-scoped class registration '${className}'; ` +\n 'register an explicit qualified class name instead.',\n );\n }\n\n return config;\n}\n\n/** @internal Used by TenantScoped; direct callers must use the string API. */\nexport function registerTenantScopedConstructor(\n target: Function,\n config: Partial<TenantScopedConfig> = {},\n): void {\n const resolved = { ...DEFAULT_CONFIG, ...config };\n unregisteredDecoratorRegistrations.set(target.name, resolved);\n tenantScopedClasses.set(target.name, resolved);\n}\n\n/**\n * Register a class as tenant-scoped with the given configuration.\n *\n * Call this directly when you cannot use decorators (e.g., third-party classes\n * or plain objects in tests). Defaults from `DEFAULT_CONFIG` are merged over\n * any omitted options. `@TenantScoped()` has its own constructor-aware mirror\n * and reconciles its authoritative policy in core.\n *\n * A simple selector binds to its exact core constructor when one owner is\n * uniquely resolvable, including when registration happens before core. Once\n * bound it remains attached to that constructor if a same-name peer appears.\n * If core clears that constructor and reuses its qualified name, the selector\n * fails closed until the caller explicitly unregisters and re-registers it.\n * If ownership is ambiguous before binding, interception fails closed until a\n * caller registers an explicit qualified selector. Calling this again for the\n * same selector overwrites that selector's previous entry.\n *\n * @param className - A simple class name (e.g., `'Document'`) or exact core\n * qualified name (e.g., `'@package/name:Document'`).\n * @param config - Partial tenancy configuration; omitted fields receive defaults.\n *\n * @example\n * ```typescript\n * // Manually register a class (e.g., for testing)\n * registerTenantScopedClass('Document', { mode: 'optional' });\n * ```\n *\n * @see TenantScoped\n * @see unregisterTenantScopedClass\n */\nexport function registerTenantScopedClass(\n className: string,\n config: Partial<TenantScopedConfig> = {},\n): void {\n const resolved = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n tenantScopedClasses.set(className, resolved);\n\n if (isQualifiedClassName(className)) {\n directQualifiedRegistrations.set(className, resolved);\n return;\n }\n\n directSimpleRegistrations.set(className, resolved);\n const existingBinding = directSimpleBindings.get(className);\n if (existingBinding && !isCurrentDirectSimpleBinding(existingBinding)) {\n directSimpleBindings.delete(className);\n }\n bindDirectSimpleRegistration(className);\n}\n\n/**\n * Remove a class from the tenant-scoped registry.\n *\n * Primarily intended for test teardown — use `clearTenantScopedRegistry()` to\n * reset the entire registry at once.\n *\n * @param className - The class name to remove (e.g., `'Document'`).\n *\n * @see clearTenantScopedRegistry\n * @see registerTenantScopedClass\n */\nexport function unregisterTenantScopedClass(className: string): void {\n tenantScopedClasses.delete(className);\n if (isQualifiedClassName(className)) {\n directQualifiedRegistrations.delete(className);\n return;\n }\n\n directSimpleRegistrations.delete(className);\n directSimpleBindings.delete(className);\n unregisteredDecoratorRegistrations.delete(className);\n}\n\n/**\n * Return a shallow copy of a config so callers can never mutate the stored\n * registration. The same backing object is shared by the base and every\n * inheriting descendant, so handing out the reference would let an accidental\n * caller mutation silently corrupt the base (and all children). (#1598 review)\n */\nfunction cloneConfig(config: TenantScopedConfig): TenantScopedConfig {\n return { ...config };\n}\n\n/**\n * Resolve a class's OWN tenancy configuration — no STI inheritance, EXACT name\n * match only.\n *\n * Checks the registration mechanisms in order: an explicit direct selector,\n * then core's declared policy. `@TenantScoped()` reconciles its policy in core;\n * its simple-name mirror is used only for unregistered test doubles.\n *\n * Lookups are by exact name only — no simple-name fallback — so a qualified\n * lookup (e.g. `@happyvertical/smrt-affiliates:Payout`, explicitly not scoped)\n * can never strip its namespace and match a same-simple-name scoped class in\n * another package (e.g. `@happyvertical/smrt-commerce:Payout`). (#1598 review)\n */\nfunction getDirectTenantScopedConfig(\n className: string,\n): TenantScopedConfig | undefined {\n // Core marks caught silent-manifest/runtime-decorator conflicts invalid.\n // Check before the simple-name decorator mirror so every identity path\n // fails closed rather than falling through to an unscoped operation.\n ObjectRegistry.assertTenantScopedRegistrationValid(className);\n // 1. Explicit direct qualified selector.\n const directQualified = directQualifiedRegistrations.get(className);\n if (directQualified) {\n return cloneConfig(directQualified);\n }\n\n const registered = isQualifiedClassName(className)\n ? ObjectRegistry.getClassByQualifiedName(className)\n : ObjectRegistry.getClass(className);\n\n // A direct simple selector can bind lazily after registration-before-core.\n // It is never inferred from a qualified name when more than one core class\n // owns that simple name.\n if (registered) {\n const simple = registered.name;\n const bound = directSimpleBindings.get(simple);\n if (bound) {\n if (\n bound.qualifiedName === className &&\n bound.constructor === registered.constructor\n ) {\n return cloneConfig(directSimpleRegistrations.get(simple)!);\n }\n // Core can clear and re-register a qualified name with a different\n // constructor. Never transfer the old selector binding to it: the caller\n // must explicitly unregister/re-register after that lifecycle reset.\n if (!isCurrentDirectSimpleBinding(bound)) {\n throw new Error(\n `Stale tenant-scoped class registration '${simple}'; ` +\n 'unregister and register it again for the current constructor.',\n );\n }\n }\n if (!bound && directSimpleRegistrations.has(simple)) {\n const matches = ObjectRegistry.findClassesByName(simple);\n if (matches.length > 1) {\n throw new Error(\n `Ambiguous tenant-scoped class registration '${simple}'; ` +\n 'register an explicit qualified class name instead.',\n );\n }\n bindDirectSimpleRegistration(simple);\n const rebound = directSimpleBindings.get(simple);\n if (\n rebound?.qualifiedName === className &&\n rebound.constructor === registered.constructor\n ) {\n return cloneConfig(directSimpleRegistrations.get(simple)!);\n }\n }\n }\n\n if (!isQualifiedClassName(className)) {\n // Explicit direct selectors retain their established precedence. For\n // plain-object/test-double paths this is the historical simple-selector\n // fallback, subject to the existing ambiguity checks.\n const directSimple = getDirectSimpleRegistration(className);\n if (directSimple) return cloneConfig(directSimple);\n }\n\n // 2. Core registry (@smrt({ tenantScoped: true }) pattern - Issue #688).\n // findClass() resolves qualified names package-safely, so this branch is\n // already disambiguated.\n const coreConfig = ObjectRegistry.getTenantScopedConfig(className);\n if (coreConfig) {\n // Convert core config to TenantScopedConfig format\n return {\n mode: coreConfig.mode,\n field: coreConfig.field,\n autoFilter: coreConfig.autoFilter,\n autoPopulate: coreConfig.autoPopulate,\n allowSuperAdminBypass: coreConfig.allowSuperAdminBypass,\n };\n }\n\n // A decorator mirror is only authoritative when core has no registration.\n // A registered unqualified consumer still has a canonical simple identity.\n if (!registered && !isQualifiedClassName(className)) {\n const decoratorConfig = unregisteredDecoratorRegistrations.get(className);\n if (decoratorConfig) return cloneConfig(decoratorConfig);\n }\n\n return undefined;\n}\n\n/**\n * Resolve tenancy configuration inherited from an STI/ancestor class.\n *\n * `@TenantScoped` (and `@smrt({ tenantScoped })`) register ONLY the exact class\n * decorated — recognition does NOT propagate to subclasses. Before #1596 this\n * meant an STI child with its own collection (the child is the collection's\n * `_itemClass`) was treated as non-tenant-scoped at runtime: the interceptor\n * skipped tenant filtering on its `list()`/`get()` (cross-tenant reads), skipped\n * tenant population in `beforeSave`, and skipped the raw-SQL policy. Manual\n * re-declaration on every child was the fragile pattern that already bit images\n * (#1407) and messages.\n *\n * We now walk the STI inheritance chain so any descendant of a tenant-scoped\n * base is recognized automatically and inherits the base's config. A subclass\n * of a tenant-scoped class is always itself tenant-scoped — there is no safe\n * reason for it to opt out — so the walk intentionally covers any inheritance\n * (the motivating leak is STI child collections, but this is correct for CTI\n * hierarchies too).\n *\n * Ancestors are walked from nearest-to-self toward the root, returning the\n * first tenant-scoped ancestor's config so a closer ancestor wins. The class's\n * OWN declaration is resolved by the direct lookup in `getTenantScopedConfig`\n * and always takes precedence over anything inherited here.\n */\nfunction getInheritedTenantScopedConfig(\n className: string,\n): TenantScopedConfig | undefined {\n // getInheritanceChain returns [root, ..., self] (qualified names where the\n // class has package context). It is cached by core and only reached here when\n // the direct lookup misses, so the per-call cost on non-tenant classes is a\n // cache hit plus this short loop. Returns [] for unregistered classes.\n const chain = ObjectRegistry.getInheritanceChain(className);\n // chain[length - 1] is the class itself (already covered by the direct\n // lookup); walk its ancestors from nearest to root.\n for (let i = chain.length - 2; i >= 0; i--) {\n const ancestor = chain[i];\n\n // Exact, package-safe match first — covers `@smrt({ tenantScoped })` bases\n // (resolved through the core registry by qualified name) and any class\n // whose @TenantScoped key matches the chain entry verbatim.\n const direct = getDirectTenantScopedConfig(ancestor);\n if (direct) {\n return direct;\n }\n\n // Do not bridge a qualified ancestor back to a simple registration here.\n // The exact lookup above reaches the core declaration reconciled by the\n // decorator. Stripping would let an unrelated same-name peer lend its\n // direct or decorator policy to this inheritance chain.\n }\n return undefined;\n}\n\n/**\n * Retrieve the resolved tenancy configuration for a class.\n *\n * Resolution order:\n * 1. The class's OWN declaration — local `@TenantScoped()` registry first, then\n * the core `@smrt({ tenantScoped: true })` registry.\n * 2. STI inheritance — the nearest tenant-scoped ancestor's config (#1596).\n *\n * A class that declares its own tenancy never reaches step 2, so an explicit\n * child `@TenantScoped` always overrides the inherited base config.\n *\n * @param className - The class name to look up.\n * @returns The `TenantScopedConfig` if the class is tenant-scoped directly or\n * by inheritance, or `undefined` if it is not.\n *\n * @see isTenantScopedClass\n * @see getAllTenantScopedClasses\n */\nexport function getTenantScopedConfig(\n className: string,\n): TenantScopedConfig | undefined {\n // A class's own @TenantScoped / @smrt({ tenantScoped }) declaration wins.\n const direct = getDirectTenantScopedConfig(className);\n if (direct) {\n return direct;\n }\n // Otherwise inherit recognition from a tenant-scoped STI ancestor (#1596).\n return getInheritedTenantScopedConfig(className);\n}\n\n/**\n * Return `true` if the named class is tenant-scoped — directly (via\n * `@TenantScoped()` / `@smrt({ tenantScoped: true })`) or by inheriting from a\n * tenant-scoped STI ancestor (#1596).\n *\n * @param className - The class name to look up (e.g., `'Document'`).\n * @returns `true` if the class is tenant-scoped by any mechanism.\n *\n * @see getTenantScopedConfig\n * @see registerTenantScopedClass\n */\nexport function isTenantScopedClass(className: string): boolean {\n return getTenantScopedConfig(className) !== undefined;\n}\n\n/**\n * Return a snapshot of all classes registered via `@TenantScoped()`.\n *\n * Returns a new `Map` so mutations to the returned value do not affect the\n * internal registry. Note that classes registered only through the core\n * `ObjectRegistry` (`@smrt({ tenantScoped: true })`) are **not** included in\n * this map.\n *\n * @returns A copy of the local tenant-scoped class registry, keyed by class name.\n *\n * @see isTenantScopedClass\n * @see getTenantScopedConfig\n */\nexport function getAllTenantScopedClasses(): Map<string, TenantScopedConfig> {\n return new Map(tenantScopedClasses);\n}\n\n/**\n * Remove all entries from the local tenant-scoped class registry.\n *\n * Intended for test teardown via `resetTenancy()`. Does not affect\n * registrations held by the core `ObjectRegistry`.\n *\n * @see resetTenancy\n * @see unregisterTenantScopedClass\n */\nexport function clearTenantScopedRegistry(): void {\n tenantScopedClasses.clear();\n directSimpleRegistrations.clear();\n directQualifiedRegistrations.clear();\n directSimpleBindings.clear();\n unregisteredDecoratorRegistrations.clear();\n}\n","/**\n * Shared tenancy-enabled flag.\n *\n * Holds the single boolean toggled by `enableTenancy()` / `disableTenancy()`.\n * It lives in its own leaf module (importing nothing from the package) so that\n * both `interceptor.ts` and `entry-point.ts` can read it without forming a\n * circular import: `interceptor.ts` imports `runTenantScopedEntryPoint` from\n * `entry-point.ts`, and `entry-point.ts` needs the enabled flag — routing the\n * flag through here keeps that dependency one-directional.\n */\n\nlet enabled = false;\n\n/**\n * Set the global tenancy-enabled flag. Internal — called by `enableTenancy()` /\n * `disableTenancy()` in `interceptor.ts`.\n *\n * @param value - `true` to mark tenancy enabled, `false` to clear it.\n */\nexport function setTenancyEnabled(value: boolean): void {\n enabled = value;\n}\n\n/**\n * Return `true` if tenant enforcement is currently active.\n *\n * @returns Whether `enableTenancy()` has been called without a later\n * `disableTenancy()`.\n */\nexport function isTenancyEnabled(): boolean {\n return enabled;\n}\n","/**\n * Fail-closed tenant-context establishment for non-web entry points (#1554).\n *\n * The SvelteKit/Express adapters establish tenant context from the authenticated\n * request principal, so the web surface of a `@TenantScoped({ mode: 'optional' })`\n * model never reads across tenants without an active context. A generated\n * in-process entry point has no request principal, so an invocation with no\n * active context would fall through the interceptor's optional-mode\n * pass-through and return rows across **all** tenants.\n *\n * `runTenantScopedEntryPoint()` closes that gap. `@happyvertical/smrt-core`'s\n * `MCPGenerator` is the only in-repo generated surface that wraps its\n * per-tool execution in this gate today (via `setTenantEntryPointRunner`\n * below). Core's `CLIGenerator`, which used to wrap its per-command execution\n * in the same gate, was retired as unused public API (#2664); the live local\n * CLI transport (`packages/cli/src/cli-generator.ts`, the shipped `smrt\n * <object>:<action>` binary) has never called this gate and is not\n * tenant-isolation fail-closed today.\n *\n * @see createCliContext for a hand-wired CLI runner (resolveTenantId,\n * super-admin) a consuming application can use directly — independent of\n * the generated-surface gate above and unaffected by #2664.\n */\n\nimport {\n hasTenantContext,\n isSystemContext,\n TenantContextError,\n withSystemContext,\n withTenant,\n} from './context.js';\nimport { isTenancyEnabled } from './enabled-state.js';\nimport { isTenantScopedClass } from './registry.js';\n\n/**\n * Inputs for {@link runTenantScopedEntryPoint}.\n *\n * Provide **either** `className` (the gate resolves tenant-scoping from the\n * authoritative tenancy registry — the same source the interceptor uses, so it\n * covers both `@TenantScoped` and `@smrt({ tenantScoped })` registrations) or an\n * explicit `tenantScoped` boolean (when the caller already resolved it, e.g. a\n * build-time generated surface). An explicit boolean wins when both are given.\n */\nexport interface TenantEntryPointOptions {\n /**\n * Class name of the target model. When provided, tenant-scoping is resolved\n * via `isTenantScopedClass(className)`.\n */\n className?: string;\n\n /**\n * Explicit tenant-scoping decision. Overrides `className` resolution when set.\n * Non-scoped models always pass through unchanged — the gate is a no-op.\n */\n tenantScoped?: boolean;\n\n /**\n * Explicit operator-provided tenant selector (CLI `--tenant <id>`, MCP\n * `context.tenantId`). When present (and no context is already active) the\n * function runs inside this tenant's context.\n */\n tenantId?: string | null;\n\n /**\n * Explicit operator opt-in to cross-tenant / system access (CLI\n * `--all-tenants`, an MCP host that trusts the caller as an operator). When\n * set the function runs in system context, bypassing tenant filtering.\n *\n * @default false\n */\n allowCrossTenant?: boolean;\n\n /**\n * Human-facing surface name used in the fail-closed error message, e.g.\n * `'CLI'` or `'MCP'`.\n *\n * @default 'entry point'\n */\n surface?: string;\n}\n\n/**\n * Run `fn` inside an appropriate tenant context for a generated in-process\n * entry point (MCP today, see the module docblock above), failing closed for\n * tenant-scoped models when no authorized context can be established.\n *\n * Resolution order (tenant-scoped models only):\n * 1. A tenant context is already active, or an explicit `withSystemContext()`\n * bypass is in effect (e.g. `runAsSystem()`, migrations) → run as-is.\n * 2. `allowCrossTenant` was explicitly set → run in system context. Checked\n * before `tenantId` so an explicit cross-tenant opt-in wins over a default\n * principal/host tenant rather than being silently scoped.\n * 3. An explicit `tenantId` was provided → run inside that tenant.\n * 4. Tenancy is enabled but none of the above → **throw** `TenantContextError`\n * (the fail-closed branch — never silently read across tenants).\n * 5. Tenancy is disabled (single-/no-tenant deployment) → pass through.\n *\n * Non-tenant-scoped models always pass straight through.\n *\n * @param options - {@link TenantEntryPointOptions}.\n * @param fn - The command/tool body to execute.\n * @returns The resolved value of `fn`.\n * @throws {TenantContextError} When a tenant-scoped model is reached with\n * tenancy enabled and no tenant/cross-tenant selector.\n */\nexport async function runTenantScopedEntryPoint<T>(\n options: TenantEntryPointOptions,\n fn: () => Promise<T>,\n): Promise<T> {\n const {\n className,\n tenantScoped,\n tenantId,\n allowCrossTenant = false,\n surface = 'entry point',\n } = options;\n\n // Resolve tenant-scoping: an explicit boolean wins; otherwise consult the\n // authoritative tenancy registry by class name (matches the interceptor).\n const scoped =\n typeof tenantScoped === 'boolean'\n ? tenantScoped\n : className\n ? isTenantScopedClass(className)\n : false;\n\n // Non-scoped models run as-is. So do calls already inside a tenant context\n // (an upstream handle) or an explicit system-context bypass — the interceptor\n // honors `withSystemContext()` (migrations, `runAsSystem()`), so the gate must\n // not fail-close over it (hasTenantContext() is false for the system marker).\n if (!scoped) return fn();\n if (hasTenantContext() || isSystemContext()) return fn();\n\n // Explicit operator opt-in to cross-tenant access. Checked before the tenant\n // selector so a deliberate `--all-tenants` / `allowCrossTenant` overrides a\n // default host/principal tenant instead of being silently scoped to it.\n if (allowCrossTenant) {\n return withSystemContext(fn);\n }\n\n // Explicit tenant selector.\n if (typeof tenantId === 'string' && tenantId) {\n return withTenant({ tenantId }, fn);\n }\n\n // Fail closed: tenancy is on but the caller gave us nothing to scope by.\n if (isTenancyEnabled()) {\n throw new TenantContextError(\n `Tenant context required for tenant-scoped access via ${surface}. ` +\n 'Pass an explicit tenant (e.g. --tenant <id> / a tenantId) or opt into ' +\n 'cross-tenant access (e.g. --all-tenants) to read across all tenants.',\n );\n }\n\n // Tenancy disabled → single-tenant deployment, pass through.\n return fn();\n}\n","/**\n * Tenant Interceptor - Core enforcement mechanism\n *\n * Registers with GlobalInterceptors in smrt-core to automatically:\n * - Filter queries by tenant ID\n * - Validate tenant context on save/delete\n * - Block or audit raw SQL on tenant-scoped classes\n *\n * @see https://github.com/happyvertical/smrt/issues/675\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport type { SmrtObject } from '@happyvertical/smrt-core';\nimport {\n type CollectionInterceptor,\n type DispatchBus,\n GlobalInterceptors,\n type InterceptorContext,\n type ListOptions,\n type QueryInterceptResult,\n type QueryOptions,\n resolveGetStringFilter,\n setDispatchTenantResolver,\n setTenantEntryPointRunner,\n setTenantScopedClassResolver,\n} from '@happyvertical/smrt-core';\nimport {\n getCurrentTenant,\n getTenantId,\n isSuperAdminBypass,\n isSystemContext,\n TenantContextError,\n TenantIsolationError,\n} from './context.js';\nimport { isTenancyEnabled, setTenancyEnabled } from './enabled-state.js';\nimport { runTenantScopedEntryPoint } from './entry-point.js';\nimport { getTenantScopedConfig, isTenantScopedClass } from './registry.js';\n\nconst logger = createLogger({ level: 'info' });\n\n/**\n * Policy controlling what happens when raw SQL is executed against a\n * tenant-scoped class without an explicit bypass.\n *\n * - `'throw'` — Raises a `TenantIsolationError` (most secure; default).\n * - `'warn'` — Logs a `console.warn` but allows the query to proceed (useful\n * during migration periods).\n * - `'allow'` — Silently allows the query; not recommended for production.\n *\n * @see TenantInterceptorOptions.rawQueryPolicy\n * @see enableTenancy\n */\nexport type RawQueryPolicy = 'throw' | 'warn' | 'allow';\n\n/**\n * Configuration options accepted by `createTenantInterceptor()` and\n * `enableTenancy()`.\n *\n * All options are optional; reasonable defaults are applied. The callback\n * hooks (`onRawQuery`, `onMissingContext`, `onIsolationViolation`) are useful\n * for logging and alerting without altering the enforcement behaviour.\n *\n * @see createTenantInterceptor\n * @see enableTenancy\n */\nexport interface TenantInterceptorOptions {\n /**\n * Policy for raw SQL queries on tenant-scoped classes\n * - 'throw': Throw error (most secure, default)\n * - 'warn': Log warning but allow (for migration)\n * - 'allow': Silently allow (not recommended for production)\n * @default 'throw'\n */\n rawQueryPolicy?: RawQueryPolicy;\n\n /**\n * Called when a raw query is attempted on a tenant-scoped class\n * Useful for logging/auditing\n */\n onRawQuery?: (\n className: string,\n sql: string,\n context: InterceptorContext,\n ) => void;\n\n /**\n * Called when tenant context is missing for a tenant-scoped operation\n */\n onMissingContext?: (\n className: string,\n operation: string,\n context: InterceptorContext,\n ) => void;\n\n /**\n * Called when an isolation violation is detected\n */\n onIsolationViolation?: (\n className: string,\n expectedTenantId: string,\n actualTenantId: string,\n context: InterceptorContext,\n ) => void;\n\n /**\n * DispatchBus instance for emitting provisioning events on lifecycle changes.\n * When provided along with directoryClasses, afterSave/afterDelete hooks\n * emit dispatches like `directory.membership.created`.\n */\n dispatchBus?: DispatchBus;\n\n /**\n * Class names to emit directory dispatches for on save/delete lifecycle events.\n * Only classes listed here will trigger dispatch emissions.\n * @example ['Tenant', 'Membership', 'User']\n */\n directoryClasses?: string[];\n}\n\nconst DEFAULT_OPTIONS: TenantInterceptorOptions = {\n rawQueryPolicy: 'throw',\n};\n\nfunction getTenancyIdentity(\n className: string,\n context: InterceptorContext,\n): string {\n return context.qualifiedClassName ?? className;\n}\n\n/**\n * Extract a plain-object snapshot of an instance for dispatch payloads.\n *\n * Prefers `toJSON()` when available (all real SmrtObject instances) because\n * it returns only data fields and excludes internal handles like `_db`, `_ai`,\n * and `_fs` which may contain circular references (e.g. connection pools with\n * Timeout objects).\n *\n * @see https://github.com/happyvertical/smrt/issues/946\n */\nfunction serializeInstance(\n instance: SmrtObject,\n className: string,\n): Record<string, unknown> {\n // Documented exception to the \"never call toJSON() directly\" convention\n // (docs/content/standards.md §7): the interceptor must serialize whatever\n // instance is handed to it, including workspace stubs and plain-object\n // doubles used in unit tests whose classes may not extend SmrtObject and\n // therefore have no `transformJSON()` hook. Using `toJSON()` here is a\n // duck-typed fallback — when present, it strips framework-internal handles\n // for us; when absent, we fall through to manual key iteration below.\n const maybeToJSON = (instance as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJSON === 'function') {\n return {\n className,\n ...(maybeToJSON.call(instance) as Record<string, unknown>),\n };\n }\n\n // Fallback for plain-object stubs (e.g. in unit tests):\n // skip functions and framework-internal properties\n const result: Record<string, unknown> = { className };\n const record = instance as unknown as Record<string, unknown>;\n for (const key of Object.keys(instance)) {\n const value = record[key];\n if (typeof value !== 'function') {\n result[key] = value;\n }\n }\n return result;\n}\n\n/**\n * Create a `CollectionInterceptor` that enforces tenant isolation on all\n * `SmrtCollection` operations.\n *\n * The returned interceptor hooks into the smrt-core `GlobalInterceptors`\n * pipeline at priority 100 (runs before all other interceptors) and\n * handles the following lifecycle hooks:\n *\n * | Hook | Behaviour |\n * |---------------|-----------|\n * | `beforeList` | Injects tenant filter into `WHERE`; validates explicit filters. |\n * | `beforeGet` | Resolves string lookups (id vs slug) and adds the tenant predicate. |\n * | `beforeSave` | Auto-populates `tenantId`; validates existing values. |\n * | `beforeDelete`| Validates the instance's `tenantId` matches context. |\n * | `beforeQuery` | Enforces `rawQueryPolicy` on raw SQL calls. |\n * | `afterSave` | Emits `directory.<class>.created/updated` via `dispatchBus`. |\n * | `afterDelete` | Emits `directory.<class>.deleted` via `dispatchBus`. |\n *\n * Use `enableTenancy()` to register the interceptor globally. Call this\n * directly only when you need multiple interceptor instances (e.g., for\n * isolated tests or feature flags).\n *\n * @param options - Configuration for the interceptor.\n * @returns A `CollectionInterceptor` ready to be registered with\n * `GlobalInterceptors.register()`.\n *\n * @example\n * ```typescript\n * import { createTenantInterceptor } from '@happyvertical/smrt-tenancy';\n * import { GlobalInterceptors } from '@happyvertical/smrt-core';\n *\n * const interceptor = createTenantInterceptor({ rawQueryPolicy: 'warn' });\n * GlobalInterceptors.register(interceptor);\n * ```\n *\n * @see enableTenancy\n * @see TenantInterceptorOptions\n */\nexport function createTenantInterceptor(\n options: TenantInterceptorOptions = {},\n): CollectionInterceptor {\n const opts = { ...DEFAULT_OPTIONS, ...options };\n\n return {\n name: 'smrt-tenancy',\n priority: 100, // High priority - should run first\n\n /**\n * Before list: Add tenant filter to queries\n */\n beforeList(\n className: string,\n listOptions: ListOptions,\n context: InterceptorContext,\n ): ListOptions | undefined {\n // Check if this class is tenant-scoped\n const tenancyIdentity = getTenancyIdentity(className, context);\n if (!isTenantScopedClass(tenancyIdentity)) {\n return; // Not tenant-scoped, pass through\n }\n\n // Check for super admin bypass\n if (isSuperAdminBypass()) {\n return; // Bypass enabled, pass through\n }\n\n // Check for system context (explicit bypass via withSystemContext)\n if (isSystemContext()) {\n return; // System context bypasses tenant checks\n }\n\n const config = getTenantScopedConfig(tenancyIdentity);\n const tenantContext = getCurrentTenant();\n\n // If no tenant context and mode is 'required', throw\n if (!tenantContext) {\n if (config?.mode === 'required') {\n opts.onMissingContext?.(className, 'list', context);\n throw new TenantContextError(\n `Tenant context required for listing ${className}. ` +\n `Use withTenant() or configure TenantContext middleware.`,\n );\n }\n return; // Mode is 'optional', allow without filtering\n }\n\n // Add tenant filter to where clause\n const tenantField = config?.field || 'tenantId';\n const where = listOptions.where || {};\n\n // Preserve DNF predicates (outer OR, inner AND) by applying the tenant\n // predicate to every branch. Flattening this shape into an object would\n // make one branch escape tenant scope, so validate direct tenant filters\n // branch-by-branch before adding the current tenant where absent.\n if (Array.isArray(where)) {\n if (\n where.length === 0 ||\n where.some((andGroup) => andGroup.length === 0)\n ) {\n throw new Error(\n 'Invalid DNF where clause: every OR branch must contain at least one condition',\n );\n }\n const scopedWhere = where.map((andGroup) => {\n const directValues = andGroup.flatMap((condition) => {\n if (!Object.hasOwn(condition, tenantField)) return [];\n const value = condition[tenantField];\n return Array.isArray(value) ? value : [value];\n });\n const offendingIndex = directValues.findIndex(\n (value) => value !== tenantContext.tenantId,\n );\n if (offendingIndex !== -1) {\n const offending = directValues[offendingIndex];\n opts.onIsolationViolation?.(\n className,\n tenantContext.tenantId,\n String(offending),\n context,\n );\n throw new TenantIsolationError(\n `Tenant isolation violation in ${className} query: ` +\n `context tenant is '${tenantContext.tenantId}' but query filters by '${String(offending)}'`,\n {\n tenantId: tenantContext.tenantId,\n attemptedTenantId: String(offending),\n },\n );\n }\n return directValues.length > 0\n ? andGroup\n : [...andGroup, { [tenantField]: tenantContext.tenantId }];\n });\n return { ...listOptions, where: scopedWhere };\n }\n\n // Check if tenant filter is already present\n if (tenantField in where) {\n // Validate it matches context. The filter may be a scalar\n // (`tenantId: 'x'`) or an IN-style array (`tenantId: ['x']`) —\n // smrt-core auto-converts array values to SQL IN clauses, so an\n // array containing only the context tenant is a valid filter.\n // See https://github.com/happyvertical/smrt/issues/1495\n const existingFilter = where[tenantField];\n const filterValues = Array.isArray(existingFilter)\n ? existingFilter\n : [existingFilter];\n // findIndex (not find) so a literal null/undefined filter value is\n // still flagged as a violation rather than mistaken for \"not found\"\n const offendingIndex = filterValues.findIndex(\n (value) => value !== tenantContext.tenantId,\n );\n if (offendingIndex !== -1) {\n const offending = filterValues[offendingIndex];\n opts.onIsolationViolation?.(\n className,\n tenantContext.tenantId,\n String(offending),\n context,\n );\n throw new TenantIsolationError(\n `Tenant isolation violation in ${className} query: ` +\n `context tenant is '${tenantContext.tenantId}' but query filters by '${String(offending)}'`,\n {\n tenantId: tenantContext.tenantId,\n attemptedTenantId: String(offending),\n },\n );\n }\n return; // Filter already correct\n }\n\n // Inject tenant filter\n return {\n ...listOptions,\n where: {\n ...where,\n [tenantField]: tenantContext.tenantId,\n },\n };\n },\n\n /**\n * Before get: Add tenant filter to single record fetches\n */\n beforeGet(\n className: string,\n filter: string | Record<string, unknown>,\n context: InterceptorContext,\n ): string | Record<string, unknown> | undefined {\n const tenancyIdentity = getTenancyIdentity(className, context);\n if (!isTenantScopedClass(tenancyIdentity)) {\n return;\n }\n\n if (isSuperAdminBypass()) {\n return;\n }\n\n // Check for system context (explicit bypass via withSystemContext)\n if (isSystemContext()) {\n return; // System context bypasses tenant checks\n }\n\n const config = getTenantScopedConfig(tenancyIdentity);\n const tenantContext = getCurrentTenant();\n\n if (!tenantContext) {\n if (config?.mode === 'required') {\n opts.onMissingContext?.(className, 'get', context);\n throw new TenantContextError(\n `Tenant context required for getting ${className}. ` +\n `Use withTenant() or configure TenantContext middleware.`,\n );\n }\n return;\n }\n\n const tenantField = config?.field || 'tenantId';\n\n // If filter is a string, resolve it exactly the way core's `get()` would\n // (UUID -> id lookup, anything else -> slug/context natural key) and add\n // the tenant predicate to whichever shape it resolves to. Rewriting every\n // string to `{ id: filter }` broke get-by-slug under a tenant context:\n // null on SQLite, a uuid cast error on PostgreSQL (#2365).\n if (typeof filter === 'string') {\n return {\n ...resolveGetStringFilter(filter),\n [tenantField]: tenantContext.tenantId,\n };\n }\n\n // Add tenant filter to object\n if (!(tenantField in filter)) {\n return {\n ...filter,\n [tenantField]: tenantContext.tenantId,\n };\n }\n\n // Validate existing filter. Like beforeList, accept scalar or\n // IN-style array filters (smrt-core auto-converts arrays to SQL IN).\n // See https://github.com/happyvertical/smrt/issues/1495\n const existingFilter = filter[tenantField];\n const filterValues = Array.isArray(existingFilter)\n ? existingFilter\n : [existingFilter];\n // findIndex (not find) so a literal null/undefined filter value is\n // still flagged as a violation rather than mistaken for \"not found\"\n const offendingIndex = filterValues.findIndex(\n (value) => value !== tenantContext.tenantId,\n );\n if (offendingIndex !== -1) {\n const offending = filterValues[offendingIndex];\n opts.onIsolationViolation?.(\n className,\n tenantContext.tenantId,\n String(offending),\n context,\n );\n throw new TenantIsolationError(\n `Tenant isolation violation in ${className} get: ` +\n `context tenant is '${tenantContext.tenantId}' but query filters by '${String(offending)}'`,\n {\n tenantId: tenantContext.tenantId,\n attemptedTenantId: String(offending),\n },\n );\n }\n\n return;\n },\n\n /**\n * Before query: Handle raw SQL on tenant-scoped classes\n */\n beforeQuery(\n className: string,\n queryOptions: QueryOptions,\n context: InterceptorContext,\n ): QueryInterceptResult | undefined {\n const tenancyIdentity = getTenancyIdentity(className, context);\n if (!isTenantScopedClass(tenancyIdentity)) {\n return;\n }\n\n // Check for explicit bypass flag\n if (queryOptions.allowRawOnTenantScoped) {\n opts.onRawQuery?.(className, queryOptions.sql, context);\n return; // Explicitly allowed\n }\n\n if (isSuperAdminBypass()) {\n opts.onRawQuery?.(className, queryOptions.sql, context);\n return;\n }\n\n // Check for system context (explicit bypass via withSystemContext)\n if (isSystemContext()) {\n opts.onRawQuery?.(className, queryOptions.sql, context);\n return;\n }\n\n // Handle based on policy\n const message =\n `Raw SQL query attempted on tenant-scoped class ${className}. ` +\n `Use list()/get() for automatic tenant filtering, or call ` +\n `query() with { allowRawOnTenantScoped: true } if you're handling ` +\n `tenant filtering manually.`;\n\n opts.onRawQuery?.(className, queryOptions.sql, context);\n\n switch (opts.rawQueryPolicy) {\n case 'throw':\n throw new TenantIsolationError(message);\n\n case 'warn':\n logger.warn(`[smrt-tenancy] WARNING: ${message}`);\n return;\n default:\n return;\n }\n },\n\n /**\n * Before save: Validate tenant ID is set and matches context\n */\n beforeSave(instance: SmrtObject, context: InterceptorContext): void {\n // Use context.className which is always correct\n // (instance.constructor.name may not match for proxies or plain objects in tests)\n const className = context.className;\n\n // Stash isNew flag for afterSave dispatch detection\n if (opts.directoryClasses?.includes(className)) {\n const id = (instance as unknown as Record<string, unknown>).id;\n context.metadata = {\n ...context.metadata,\n _directoryIsNew: id === undefined || id === null,\n };\n }\n\n const tenancyIdentity = getTenancyIdentity(className, context);\n if (!isTenantScopedClass(tenancyIdentity)) {\n return;\n }\n\n if (isSuperAdminBypass()) {\n return;\n }\n\n // Check for system context (explicit bypass via withSystemContext)\n if (isSystemContext()) {\n return; // System context bypasses tenant checks\n }\n\n const config = getTenantScopedConfig(tenancyIdentity);\n const tenantField = config?.field || 'tenantId';\n const instanceRecord = instance as unknown as Record<string, unknown>;\n const instanceTenantId = instanceRecord[tenantField];\n\n const tenantContext = getCurrentTenant();\n\n // Check if tenant context is required\n if (!tenantContext) {\n if (config?.mode === 'required') {\n opts.onMissingContext?.(className, 'save', context);\n throw new TenantContextError(\n `Tenant context required for saving ${className}. ` +\n `Use withTenant() or configure TenantContext middleware.`,\n );\n }\n return; // Mode is 'optional'\n }\n\n // Auto-populate tenant ID if not set\n if (!instanceTenantId && config?.autoPopulate !== false) {\n instanceRecord[tenantField] = tenantContext.tenantId;\n return;\n }\n\n // Validate tenant ID matches context\n if (instanceTenantId && instanceTenantId !== tenantContext.tenantId) {\n const attemptedTenantId = String(instanceTenantId);\n opts.onIsolationViolation?.(\n className,\n tenantContext.tenantId,\n attemptedTenantId,\n context,\n );\n throw new TenantIsolationError(\n `Tenant isolation violation: cannot save ${className} with ` +\n `tenantId '${attemptedTenantId}' in context of tenant '${tenantContext.tenantId}'`,\n {\n tenantId: tenantContext.tenantId,\n attemptedTenantId,\n },\n );\n }\n },\n\n /**\n * Before delete: Validate instance belongs to current tenant\n */\n beforeDelete(instance: SmrtObject, context: InterceptorContext): void {\n // Use context.className which is always correct\n const className = context.className;\n\n const tenancyIdentity = getTenancyIdentity(className, context);\n if (!isTenantScopedClass(tenancyIdentity)) {\n return;\n }\n\n if (isSuperAdminBypass()) {\n return;\n }\n\n // Check for system context (explicit bypass via withSystemContext)\n if (isSystemContext()) {\n return; // System context bypasses tenant checks\n }\n\n const config = getTenantScopedConfig(tenancyIdentity);\n const tenantField = config?.field || 'tenantId';\n const instanceTenantId = (instance as unknown as Record<string, unknown>)[\n tenantField\n ];\n\n const tenantContext = getCurrentTenant();\n\n if (!tenantContext) {\n if (config?.mode === 'required') {\n opts.onMissingContext?.(className, 'delete', context);\n throw new TenantContextError(\n `Tenant context required for deleting ${className}. ` +\n `Use withTenant() or configure TenantContext middleware.`,\n );\n }\n return;\n }\n\n // Validate tenant ID matches\n if (instanceTenantId && instanceTenantId !== tenantContext.tenantId) {\n const attemptedTenantId = String(instanceTenantId);\n opts.onIsolationViolation?.(\n className,\n tenantContext.tenantId,\n attemptedTenantId,\n context,\n );\n throw new TenantIsolationError(\n `Tenant isolation violation: cannot delete ${className} with ` +\n `tenantId '${attemptedTenantId}' in context of tenant '${tenantContext.tenantId}'`,\n {\n tenantId: tenantContext.tenantId,\n attemptedTenantId,\n },\n );\n }\n },\n\n /**\n * After save: Emit directory dispatch for configured classes\n */\n async afterSave(\n instance: SmrtObject,\n context: InterceptorContext,\n ): Promise<void> {\n if (\n !opts.dispatchBus ||\n !opts.directoryClasses?.includes(context.className)\n )\n return;\n\n const instanceId = (instance as unknown as Record<string, unknown>).id;\n const sourceId = typeof instanceId === 'string' ? instanceId : undefined;\n const rawIsNew = context.metadata?._directoryIsNew;\n const isNew =\n typeof rawIsNew === 'boolean' ? rawIsNew : instanceId == null;\n const event = isNew\n ? `directory.${context.className.toLowerCase()}.created`\n : `directory.${context.className.toLowerCase()}.updated`;\n\n await opts.dispatchBus.emit(\n event,\n serializeInstance(instance, context.className),\n {\n source: 'smrt-tenancy',\n sourceId,\n },\n );\n },\n\n /**\n * After delete: Emit directory dispatch for configured classes\n */\n async afterDelete(\n instance: SmrtObject,\n context: InterceptorContext,\n ): Promise<void> {\n if (\n !opts.dispatchBus ||\n !opts.directoryClasses?.includes(context.className)\n )\n return;\n\n const instanceId = (instance as unknown as Record<string, unknown>).id;\n await opts.dispatchBus.emit(\n `directory.${context.className.toLowerCase()}.deleted`,\n serializeInstance(instance, context.className),\n {\n source: 'smrt-tenancy',\n sourceId: typeof instanceId === 'string' ? instanceId : undefined,\n },\n );\n },\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Registration Functions\n// ─────────────────────────────────────────────────────────────────────────────\n\n// The enabled flag lives in `enabled-state.ts` (a leaf module) so `entry-point.ts`\n// can read it without importing this module — breaking the otherwise-circular\n// interceptor ↔ entry-point dependency.\nlet registeredInterceptor: CollectionInterceptor | null = null;\n\n/**\n * Enable tenant enforcement globally\n *\n * Call this once at application startup to enable automatic tenant isolation.\n *\n * @param options - Configuration options\n *\n * @example\n * ```typescript\n * // In your app initialization\n * import { enableTenancy } from '@happyvertical/smrt-tenancy';\n *\n * enableTenancy({\n * rawQueryPolicy: 'throw',\n * onMissingContext: (className, operation) => {\n * console.error(`Missing tenant context for ${operation} on ${className}`);\n * }\n * });\n * ```\n */\nexport function enableTenancy(options: TenantInterceptorOptions = {}): void {\n if (isTenancyEnabled()) {\n logger.warn(\n '[smrt-tenancy] Tenancy is already enabled. Call disableTenancy() first to reconfigure.',\n );\n return;\n }\n\n registeredInterceptor = createTenantInterceptor(options);\n GlobalInterceptors.register(registeredInterceptor);\n\n // Wire the DispatchBus tenant-scope resolver (S5 #1398). Core cannot depend\n // on tenancy, so it reads the active tenant through this injected hook; the\n // bus stamps/filters dispatches by the active tenant only while tenancy is\n // enabled. Mirrors the GlobalInterceptors inversion above.\n setDispatchTenantResolver(() => getTenantId());\n\n // Wire the fail-closed tenant gate for generated in-process entry points\n // (#1554). Core's MCPGenerator invokes this runner around tenant-scoped MCP\n // execution; without it (tenancy disabled) that surface passes through\n // unchanged. Core's CLIGenerator used to invoke it too but was retired as\n // unused public API (#2664); the shipped local CLI transport\n // (packages/cli/src/cli-generator.ts) has never called it.\n setTenantEntryPointRunner(runTenantScopedEntryPoint);\n\n // Wire the tenant-scoped-class resolver so core-side fail-closed read guards\n // (generated REST read scope, #1782) recognize `@TenantScoped()`-decorated\n // classes, which record their config only in the tenancy registry.\n setTenantScopedClassResolver((className) => isTenantScopedClass(className));\n\n setTenancyEnabled(true);\n}\n\n/**\n * Disable global tenant enforcement.\n *\n * Unregisters the interceptor previously installed by `enableTenancy()` and\n * resets the internal enabled flag so `enableTenancy()` can be called again.\n * Idempotent — safe to call even when tenancy was never enabled.\n *\n * Common use-cases:\n * - Test teardown (via `resetTenancy()`).\n * - Temporarily disabling tenancy before reconfiguring with new options.\n *\n * @example\n * ```typescript\n * afterAll(() => {\n * disableTenancy();\n * });\n * ```\n *\n * @see enableTenancy\n * @see isTenancyEnabled\n * @see resetTenancy\n */\nexport function disableTenancy(): void {\n if (!isTenancyEnabled() || !registeredInterceptor) {\n return;\n }\n\n GlobalInterceptors.unregister(registeredInterceptor);\n // Clear the DispatchBus tenant resolver so the bus reverts to its no-op\n // (pre-tenancy) behavior when tenancy is disabled.\n setDispatchTenantResolver(undefined);\n // Clear the in-process tenant gate so that surface (MCP) passes through\n // (#1554).\n setTenantEntryPointRunner(undefined);\n // Clear the tenant-scoped-class resolver (#1782).\n setTenantScopedClassResolver(undefined);\n registeredInterceptor = null;\n setTenancyEnabled(false);\n}\n\n/**\n * Return `true` if tenant enforcement is currently active.\n *\n * Reflects whether `enableTenancy()` has been called and the interceptor has not\n * yet been removed by `disableTenancy()`. Re-exported from `enabled-state.ts`\n * (the shared leaf module) so the public API surface is unchanged.\n *\n * @see enableTenancy\n * @see disableTenancy\n */\nexport { isTenancyEnabled };\n","/**\n * Testing Utilities for smrt-tenancy\n *\n * Helpers for testing tenant-scoped applications.\n *\n * @example\n * ```typescript\n * import { createTestTenantContext, resetTenancy } from '@happyvertical/smrt-tenancy/testing';\n *\n * beforeEach(() => {\n * resetTenancy(); // Clear all state\n * });\n *\n * it('should filter by tenant', async () => {\n * await createTestTenantContext({ tenantId: 'tenant-1' }, async () => {\n * const docs = await collection.list({});\n * // Only tenant-1 documents\n * });\n * });\n * ```\n */\n\nimport {\n type MinimalTenantContext,\n type TenantContextData,\n withTenant,\n} from './context.js';\nimport { disableTenancy, enableTenancy } from './interceptor.js';\nimport { clearTenantScopedRegistry } from './registry.js';\n\n/**\n * Reset all tenancy state (for use in beforeEach/afterEach)\n *\n * This clears:\n * - Registered interceptors\n * - Tenant-scoped class registry\n *\n * @example\n * ```typescript\n * afterEach(() => {\n * resetTenancy();\n * });\n * ```\n */\nexport function resetTenancy(): void {\n disableTenancy();\n clearTenantScopedRegistry();\n}\n\n/**\n * Create a test tenant context and run code within it\n *\n * Convenience wrapper around withTenant() with sensible defaults for testing.\n *\n * @param context - Tenant context (can be minimal, just tenantId)\n * @param fn - Async function to run in the context\n *\n * @example\n * ```typescript\n * await createTestTenantContext({ tenantId: 'test-tenant' }, async () => {\n * const product = await collection.create({ name: 'Test' });\n * expect(product.tenantId).toBe('test-tenant');\n * });\n * ```\n */\nexport async function createTestTenantContext<T>(\n context: MinimalTenantContext | TenantContextData,\n fn: () => Promise<T>,\n): Promise<T> {\n return withTenant(context, fn);\n}\n\n/**\n * Create multiple tenant contexts for isolation testing\n *\n * @param tenantIds - Array of tenant IDs to create contexts for\n * @param fn - Function that receives an object mapping tenant IDs to context runners\n *\n * @example\n * ```typescript\n * await testTenantIsolation(['tenant-a', 'tenant-b'], async (tenants) => {\n * // Create in tenant A\n * const docA = await tenants['tenant-a'](async () => {\n * return collection.create({ title: 'A doc' });\n * });\n *\n * // Verify not visible in tenant B\n * await tenants['tenant-b'](async () => {\n * const found = await collection.get(docA.id);\n * expect(found).toBeNull();\n * });\n * });\n * ```\n */\nexport async function testTenantIsolation<T>(\n tenantIds: string[],\n fn: (\n tenants: Record<string, <R>(runner: () => Promise<R>) => Promise<R>>,\n ) => Promise<T>,\n): Promise<T> {\n const tenants: Record<string, <R>(runner: () => Promise<R>) => Promise<R>> =\n {};\n\n for (const tenantId of tenantIds) {\n tenants[tenantId] = async <R>(runner: () => Promise<R>) => {\n return withTenant({ tenantId }, runner);\n };\n }\n\n return fn(tenants);\n}\n\n/**\n * Options for `setupTestTenancy()`.\n *\n * @see setupTestTenancy\n */\nexport interface SetupTestTenancyOptions {\n /**\n * Enable tenancy interceptors\n * @default true\n */\n enableInterceptors?: boolean;\n\n /**\n * Raw query policy for tests\n * @default 'throw'\n */\n rawQueryPolicy?: 'throw' | 'warn' | 'allow';\n}\n\n/**\n * Set up tenancy for a test suite\n *\n * Call in beforeAll or at the start of tests to configure tenancy.\n *\n * @param options - Setup options\n *\n * @example\n * ```typescript\n * beforeAll(() => {\n * setupTestTenancy({ enableInterceptors: true });\n * });\n *\n * afterAll(() => {\n * resetTenancy();\n * });\n * ```\n */\nexport function setupTestTenancy(options: SetupTestTenancyOptions = {}): void {\n const { enableInterceptors = true, rawQueryPolicy = 'throw' } = options;\n\n // Clear any existing state\n resetTenancy();\n\n // Enable interceptors if requested\n if (enableInterceptors) {\n enableTenancy({ rawQueryPolicy });\n }\n}\n\n/**\n * Assert that executing `fn` throws a `TenantContextError`.\n *\n * Fails with a descriptive message if `fn` completes without throwing, or if\n * it throws a different error type. Optionally verifies that the error message\n * contains a specific substring.\n *\n * Useful for testing that business-logic code correctly rejects calls that are\n * made outside a tenant context.\n *\n * @param fn - Async function that should throw `TenantContextError`.\n * @param messageContains - Optional substring the error message must include.\n *\n * @example\n * ```typescript\n * await assertTenantContextRequired(async () => {\n * // No withTenant() in scope\n * await documentCollection.list({});\n * });\n * ```\n *\n * @see assertTenantIsolationViolation\n * @see TenantContextError\n */\nexport async function assertTenantContextRequired(\n fn: () => Promise<unknown>,\n messageContains?: string,\n): Promise<void> {\n try {\n await fn();\n throw new Error('Expected TenantContextError but no error was thrown');\n } catch (error: unknown) {\n const err = error as Error & { code?: string };\n if (err.code !== 'TENANT_CONTEXT_REQUIRED') {\n throw new Error(\n `Expected TenantContextError but got ${err.constructor.name}: ${err.message}`,\n );\n }\n if (messageContains && !err.message.includes(messageContains)) {\n throw new Error(\n `Expected error message to contain '${messageContains}' but got: ${err.message}`,\n );\n }\n }\n}\n\n/**\n * Assert that executing `fn` throws a `TenantIsolationError`.\n *\n * Fails with a descriptive message if `fn` completes without throwing, or if\n * it throws a different error type. Optionally verifies that the error message\n * contains a specific substring.\n *\n * Use this to verify that cross-tenant data access attempts are correctly\n * blocked by the interceptor.\n *\n * @param fn - Async function that should throw `TenantIsolationError`.\n * @param messageContains - Optional substring the error message must include.\n *\n * @example\n * ```typescript\n * await withTenant({ tenantId: 'tenant-a' }, async () => {\n * await assertTenantIsolationViolation(async () => {\n * // Attempt to filter by a different tenant\n * await collection.list({ where: { tenantId: 'tenant-b' } });\n * });\n * });\n * ```\n *\n * @see assertTenantContextRequired\n * @see TenantIsolationError\n */\nexport async function assertTenantIsolationViolation(\n fn: () => Promise<unknown>,\n messageContains?: string,\n): Promise<void> {\n try {\n await fn();\n throw new Error('Expected TenantIsolationError but no error was thrown');\n } catch (error: unknown) {\n const err = error as Error & { code?: string };\n if (err.code !== 'TENANT_ISOLATION_VIOLATION') {\n throw new Error(\n `Expected TenantIsolationError but got ${err.constructor.name}: ${err.message}`,\n );\n }\n if (messageContains && !err.message.includes(messageContains)) {\n throw new Error(\n `Expected error message to contain '${messageContains}' but got: ${err.message}`,\n );\n }\n }\n}\n"],"mappings":";;;;AA6DA,IAAM,iBAAqC;CACzC,MAAM;CACN,OAAO;CACP,YAAY;CACZ,cAAc;CACd,uBAAuB;AACzB;AAGA,IAAM,sCAAsB,IAAI,IAAgC;AAKhE,IAAM,4CAA4B,IAAI,IAAgC;AACtE,IAAM,+CAA+B,IAAI,IAAgC;AACzE,IAAM,uCAAuB,IAAI,IAG/B;AAKF,IAAM,qDAAqC,IAAI,IAG7C;AAEF,SAAS,qBAAqB,WAA4B;CACxD,OAAO,UAAU,SAAS,GAAG;AAC/B;AAEA,SAAS,6BAA6B,SAG1B;CACV,OACE,eAAe,wBAAwB,QAAQ,aAAa,CAAA,EACxD,gBAAgB,QAAQ;AAEhC;AAEA,SAAS,6BAA6B,WAAyB;CAE7D,IAAI,CADW,0BAA0B,IAAI,SACxC,KAAU,qBAAqB,IAAI,SAAS,GAAG;CAEpD,MAAM,UAAU,eAAe,kBAAkB,SAAS;CAC1D,IAAI,QAAQ,WAAW,KAAK,CAAC,QAAQ,EAAC,CAAE,eAAe;CAEvD,qBAAqB,IAAI,WAAW;EAClC,eAAe,QAAQ,EAAC,CAAE;EAC1B,aAAa,QAAQ,EAAC,CAAE;CAC1B,CAAC;AACH;AAEA,SAAS,4BACP,WACgC;CAChC,MAAM,SAAS,0BAA0B,IAAI,SAAS;CACtD,IAAI,CAAC,QAAQ,OAAO,KAAA;CAEpB,MAAM,UAAU,qBAAqB,IAAI,SAAS;CAClD,IAAI,WAAW,CAAC,6BAA6B,OAAO,GAClD,MAAM,IAAI,MACR,2CAA2C,UAAS,iEAEtD;CAIF,IADgB,eAAe,kBAAkB,SAC7C,CAAA,CAAQ,SAAS,GACnB,MAAM,IAAI,MACR,+CAA+C,UAAS,sDAE1D;CAGF,OAAO;AACT;AAGO,SAAS,gCACd,Q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AAI,mBAAmB,CAAC,IAAI,QAAQ,SAAS,eAAe,GAC1D,MAAM,IAAI,MACR,sCAAsC,gBAAe,aAAc,IAAI,SACzE;CAEJ;AACF"}
|
package/dist/decorators.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decorators.d.ts","sourceRoot":"","sources":["../src/decorators.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAEL,KAAK,2BAA2B,EAKjC,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAMxD;;;;;;;;GAQG;AACH,MAAM,WAAW,mBAAmB;IAClC;;;;OAIG;IACH,IAAI,CAAC,EAAE,UAAU,GAAG,UAAU,CAAC;IAE/B;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IAErB;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IAEvB;;;OAGG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;CACjC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,wBAAgB,YAAY,CAAC,OAAO,GAAE,mBAAwB,IACpD,CAAC,SAAS,QAAQ,EACxB,QAAQ,CAAC,EACT,mBAAmB,qBAAqB,KACvC,CAAC,
|
|
1
|
+
{"version":3,"file":"decorators.d.ts","sourceRoot":"","sources":["../src/decorators.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAEL,KAAK,2BAA2B,EAKjC,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAMxD;;;;;;;;GAQG;AACH,MAAM,WAAW,mBAAmB;IAClC;;;;OAIG;IACH,IAAI,CAAC,EAAE,UAAU,GAAG,UAAU,CAAC;IAE/B;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IAErB;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IAEvB;;;OAGG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;CACjC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,wBAAgB,YAAY,CAAC,OAAO,GAAE,mBAAwB,IACpD,CAAC,SAAS,QAAQ,EACxB,QAAQ,CAAC,EACT,mBAAmB,qBAAqB,KACvC,CAAC,CA6BL;AAMD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,wBAAgB,QAAQ,CAAC,OAAO,GAAE,oBAAyB,GAsCnD,2BAA2B,CAClC"}
|
package/dist/index.js
CHANGED
|
@@ -1,21 +1,28 @@
|
|
|
1
1
|
import { a as getCurrentTenant, c as isSuperAdminBypass, d as requireTenantId, f as withSuperAdminBypass, h as withTenantSync, i as enterTenantContext, l as isSystemContext, m as withTenant, n as TenantContextError, o as getTenantId, p as withSystemContext, r as TenantIsolationError, s as hasTenantContext, t as TenantContext, u as requireTenant } from "./chunks/context-CwbLwyIV.js";
|
|
2
2
|
import { n as createExpressMiddleware, r as createCliContext, t as createSvelteKitHandle } from "./chunks/adapters-B4hMNcuw.js";
|
|
3
|
-
import { _ as
|
|
3
|
+
import { _ as registerTenantScopedConstructor, a as setupTestTenancy, c as disableTenancy, d as isTenancyEnabled, f as clearTenantScopedRegistry, g as registerTenantScopedClass, h as isTenantScopedClass, i as resetTenancy, l as enableTenancy, m as getTenantScopedConfig, n as assertTenantIsolationViolation, o as testTenantIsolation, p as getAllTenantScopedClasses, r as createTestTenantContext, s as createTenantInterceptor, t as assertTenantContextRequired, u as runTenantScopedEntryPoint, v as unregisterTenantScopedClass } from "./chunks/testing-CrMnRY8M.js";
|
|
4
4
|
import { ObjectRegistry, applyPendingDecoratorRegistrations, registerCompatibleFieldDecorator } from "@happyvertical/smrt-core";
|
|
5
5
|
//#region src/__smrt-register__.ts
|
|
6
|
-
ObjectRegistry.registerPackageManifest(JSON.parse("{\"version\":\"1.0.0\",\"timestamp\":0,\"packageName\":\"@happyvertical/smrt-tenancy\",\"packageVersion\":\"0.
|
|
6
|
+
ObjectRegistry.registerPackageManifest(JSON.parse("{\"version\":\"1.0.0\",\"timestamp\":0,\"packageName\":\"@happyvertical/smrt-tenancy\",\"packageVersion\":\"0.49.0\",\"objects\":{},\"moduleType\":\"smrt\",\"smrtDependencies\":[\"@happyvertical/smrt-core\"]}"));
|
|
7
7
|
//#endregion
|
|
8
8
|
//#region src/decorators.ts
|
|
9
9
|
function TenantScoped(options = {}) {
|
|
10
10
|
return (target, decoratorContext) => {
|
|
11
11
|
applyPendingDecoratorRegistrations(target, decoratorContext);
|
|
12
|
-
const
|
|
13
|
-
registerTenantScopedClass(className, {
|
|
12
|
+
const config = {
|
|
14
13
|
mode: options.mode ?? "required",
|
|
15
14
|
field: options.field ?? "tenantId",
|
|
16
15
|
autoFilter: options.autoFilter ?? true,
|
|
17
16
|
autoPopulate: options.autoPopulate ?? true,
|
|
18
17
|
allowSuperAdminBypass: options.allowSuperAdminBypass ?? false
|
|
18
|
+
};
|
|
19
|
+
registerTenantScopedConstructor(target, config);
|
|
20
|
+
ObjectRegistry.reconcileTenantScopedConfig(target, {
|
|
21
|
+
mode: config.mode ?? "required",
|
|
22
|
+
field: config.field ?? "tenantId",
|
|
23
|
+
autoFilter: config.autoFilter ?? true,
|
|
24
|
+
autoPopulate: config.autoPopulate ?? true,
|
|
25
|
+
allowSuperAdminBypass: config.allowSuperAdminBypass ?? false
|
|
19
26
|
});
|
|
20
27
|
return target;
|
|
21
28
|
};
|
|
@@ -29,8 +36,8 @@ function tenantId(options = {}) {
|
|
|
29
36
|
...options
|
|
30
37
|
};
|
|
31
38
|
return ((targetOrValue, propertyKeyOrContext) => {
|
|
32
|
-
registerCompatibleFieldDecorator(targetOrValue, propertyKeyOrContext, (className, propertyKey) => {
|
|
33
|
-
|
|
39
|
+
registerCompatibleFieldDecorator(targetOrValue, propertyKeyOrContext, (className, propertyKey, ctor) => {
|
|
40
|
+
const fieldOptions = {
|
|
34
41
|
type: "foreignKey",
|
|
35
42
|
related: "Tenant",
|
|
36
43
|
sqlType: "UUID",
|
|
@@ -40,7 +47,8 @@ function tenantId(options = {}) {
|
|
|
40
47
|
...opts,
|
|
41
48
|
isTenantIdField: true
|
|
42
49
|
}
|
|
43
|
-
}
|
|
50
|
+
};
|
|
51
|
+
ObjectRegistry.registerFieldDecorator(className, propertyKey, fieldOptions, ctor);
|
|
44
52
|
});
|
|
45
53
|
});
|
|
46
54
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/__smrt-register__.ts","../src/decorators.ts","../src/fields.ts","../src/tenant-global-queries.ts"],"sourcesContent":["/**\n * Self-registers this package's build-time manifest before any @smrt() decorator\n * in the package fires. Fixes issue #1132: in consumer runtimes (tsx, SvelteKit\n * SSR, plain `vite dev`) the decorator's synchronous manifest lookup previously\n * missed because no step populated the global manifest cache — classes got\n * registered with zero fields and `save()` / `toJSON()` silently dropped every\n * declared property.\n *\n * Import this module as the first statement in `src/index.ts` so its top-level\n * side effect runs ahead of any class module's @smrt() decorator.\n *\n * Silent no-op in dev/test, where the vitest plugin already populates manifests\n * via a different path. Only needs to succeed in the published dist output.\n *\n * @see https://github.com/happyvertical/smrt/issues/1132\n */\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\n// During library builds, smrtPlugin replaces this entire module with generated\n// code that embeds the scanned manifest inline (#1506/#1507) — published dists\n// never resolve this URL, so downstream bundlers cannot break registration by\n// relocating the compiled module away from dist/manifest.json. The runtime\n// lookup below is the fallback for source-mode runs without that transform.\nObjectRegistry.registerPackageManifest(\n new URL('./manifest.json', import.meta.url),\n);\n","/**\n * Tenancy Decorators\n *\n * Provides class and property decorators for tenant-scoped SMRT objects.\n *\n * @example\n * ```typescript\n * import { smrt, SmrtObject } from '@happyvertical/smrt-core';\n * import { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\n *\n * @smrt()\n * @TenantScoped({ mode: 'optional' })\n * class Document extends SmrtObject {\n * @tenantId({ nullable: true })\n * tenantId: string | null = null; // null = global document\n *\n * title: string = '';\n * }\n * ```\n *\n * @see https://github.com/happyvertical/smrt/issues/675\n * @see https://github.com/happyvertical/smrt/issues/829\n */\n\nimport {\n applyPendingDecoratorRegistrations,\n type CompatiblePropertyDecorator,\n type CompatiblePropertyDecoratorContext,\n type LegacyPropertyDecoratorTarget,\n ObjectRegistry,\n registerCompatibleFieldDecorator,\n} from '@happyvertical/smrt-core';\nimport type { TenantIdFieldOptions } from './fields.js';\nimport {\n registerTenantScopedClass,\n type TenantScopedConfig,\n} from './registry.js';\n\n/**\n * Options accepted by the `@TenantScoped()` class decorator.\n *\n * All fields are optional; defaults match the most restrictive safe behaviour\n * (required mode, auto-filter and auto-populate enabled, no super-admin bypass).\n *\n * @see TenantScoped\n * @see TenantScopedConfig\n */\nexport interface TenantScopedOptions {\n /**\n * Tenancy mode for this class\n * - 'required': Must have tenant context for all operations (default)\n * - 'optional': Works with or without tenant context\n */\n mode?: 'required' | 'optional';\n\n /**\n * Field name containing tenant ID\n * @default 'tenantId'\n */\n field?: string;\n\n /**\n * Auto-filter all queries by tenant\n * @default true\n */\n autoFilter?: boolean;\n\n /**\n * Auto-populate tenant ID from context on create\n * @default true\n */\n autoPopulate?: boolean;\n\n /**\n * Allow super admin bypass for this class\n * @default false - must be explicitly enabled\n */\n allowSuperAdminBypass?: boolean;\n}\n\n/**\n * Mark a class as tenant-scoped\n *\n * This decorator registers the class with the tenancy system so that:\n * - list()/get() queries are automatically filtered by tenant\n * - save() validates tenant ID matches current context\n * - delete() validates tenant ownership\n * - Raw SQL queries trigger policy enforcement\n *\n * @param options - Configuration options\n *\n * @example Basic usage (required tenancy)\n * ```typescript\n * @smrt()\n * @TenantScoped()\n * class Document extends SmrtObject {\n * @tenantId()\n * tenantId: string = '';\n *\n * title: string = '';\n * }\n * ```\n *\n * @example With super admin bypass enabled\n * ```typescript\n * @smrt()\n * @TenantScoped({ allowSuperAdminBypass: true })\n * class AuditLog extends SmrtObject {\n * @tenantId()\n * tenantId: string = '';\n *\n * action: string = '';\n * }\n * ```\n *\n * @example Optional tenancy (works with or without context)\n * ```typescript\n * @smrt()\n * @TenantScoped({ mode: 'optional' })\n * class GlobalConfig extends SmrtObject {\n * @tenantId({ nullable: true })\n * tenantId: string | null = null; // null = global, string = tenant-specific\n *\n * key: string = '';\n * value: string = '';\n * }\n * ```\n */\nexport function TenantScoped(options: TenantScopedOptions = {}) {\n return <T extends Function>(\n target: T,\n decoratorContext?: ClassDecoratorContext,\n ): T => {\n applyPendingDecoratorRegistrations(target, decoratorContext);\n\n const className = target.name;\n\n // Merge with defaults\n const config: Partial<TenantScopedConfig> = {\n mode: options.mode ?? 'required',\n field: options.field ?? 'tenantId',\n autoFilter: options.autoFilter ?? true,\n autoPopulate: options.autoPopulate ?? true,\n allowSuperAdminBypass: options.allowSuperAdminBypass ?? false,\n };\n\n // Register with the tenancy system\n registerTenantScopedClass(className, config);\n\n // Return the class unchanged\n return target;\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Property Decorator: @tenantId\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Tenant ID property decorator\n *\n * Marks a property as the tenant identifier field. This decorator registers\n * the field metadata with ObjectRegistry, keeping the property value clean\n * (no descriptor objects that could be accidentally saved to the database).\n *\n * @param options - Field options (nullable, autoFilter, autoPopulate, etc.)\n * @returns Property decorator\n *\n * @example Basic usage (required tenancy)\n * ```typescript\n * @smrt()\n * @TenantScoped()\n * class Document extends SmrtObject {\n * @tenantId()\n * tenantId: string = '';\n *\n * title: string = '';\n * }\n * ```\n *\n * @example Nullable tenant ID (for global resources)\n * ```typescript\n * @smrt()\n * @TenantScoped({ mode: 'optional' })\n * class GlobalConfig extends SmrtObject {\n * @tenantId({ nullable: true })\n * tenantId: string | null = null; // null = global, string = tenant-specific\n *\n * key: string = '';\n * }\n * ```\n *\n * @see https://github.com/happyvertical/smrt/issues/829 - Why decorators over field helpers\n */\nexport function tenantId(options: TenantIdFieldOptions = {}) {\n const opts = {\n autoFilter: true,\n required: true,\n autoPopulate: true,\n nullable: false,\n ...options,\n };\n\n return ((\n targetOrValue: LegacyPropertyDecoratorTarget | undefined,\n propertyKeyOrContext: CompatiblePropertyDecoratorContext<unknown, unknown>,\n ) => {\n registerCompatibleFieldDecorator(\n targetOrValue,\n propertyKeyOrContext,\n (className, propertyKey) => {\n ObjectRegistry.registerFieldDecorator(className, propertyKey, {\n type: 'foreignKey',\n related: 'Tenant',\n sqlType: 'UUID',\n required: opts.required,\n nullable: opts.nullable,\n __tenancy: {\n ...opts,\n isTenantIdField: true,\n },\n });\n },\n );\n }) as CompatiblePropertyDecorator;\n}\n","/**\n * Tenancy Field Types and Utilities\n *\n * This module provides types and utility functions for tenant ID fields.\n * The actual field decorator is in decorators.ts.\n *\n * @see https://github.com/happyvertical/smrt/issues/675\n * @see https://github.com/happyvertical/smrt/issues/829\n */\n\n/**\n * Options for the `@tenantId()` property decorator.\n *\n * Controls how the decorated field interacts with the tenancy interceptor.\n * All options default to the strictest safe values: auto-filter on, required,\n * auto-populate on, not nullable.\n *\n * @see tenantId\n * @see TenantScopedOptions\n */\nexport interface TenantIdFieldOptions {\n /**\n * Auto-filter queries by this field\n * @default true\n */\n autoFilter?: boolean;\n\n /**\n * Require this field to have a value on save\n * @default true\n */\n required?: boolean;\n\n /**\n * Auto-populate from context on create if not set\n * @default true\n */\n autoPopulate?: boolean;\n\n /**\n * Allow null values (for global resources)\n * @default false\n */\n nullable?: boolean;\n}\n\n// Symbol to identify tenantId fields\nexport const TENANT_ID_SYMBOL = Symbol('tenantId');\n\n/**\n * Internal field descriptor stored in `ObjectRegistry` when `@tenantId()` is\n * applied to a property.\n *\n * Consumers should use `isTenantIdField()` and `getTenantIdFieldOptions()`\n * to inspect these descriptors rather than reading the raw properties directly.\n *\n * @see isTenantIdField\n * @see getTenantIdFieldOptions\n */\nexport interface TenantIdFieldDefinition {\n /** Field type marker */\n type: 'foreignKey';\n /** Reference to Tenant class (placeholder - actual class resolved at runtime) */\n reference: 'Tenant';\n /** SQL type */\n sqlType: 'UUID';\n /** Field is required */\n required: boolean;\n /** Field allows null */\n nullable: boolean;\n /** Tenancy-specific options */\n __tenancy: TenantIdFieldOptions & { isTenantIdField: true };\n}\n\n/**\n * Return `true` if the given field definition was produced by the `@tenantId()`\n * decorator (i.e., it has an `__tenancy.isTenantIdField` marker).\n *\n * Used internally by the interceptor and code generators to locate the tenant\n * ID field on a class without knowing its property name in advance.\n *\n * @param field - A raw field definition object, typically from `ObjectRegistry`.\n * @returns `true` if `field` is a tenant ID field definition, `false` otherwise.\n *\n * @example\n * ```typescript\n * const fields = ObjectRegistry.getFields('Document');\n * const tenantField = Object.entries(fields).find(([, def]) => isTenantIdField(def));\n * ```\n *\n * @see getTenantIdFieldOptions\n * @see TenantIdFieldDefinition\n */\nexport function isTenantIdField(field: unknown): boolean {\n if (!field || typeof field !== 'object') {\n return false;\n }\n const def = field as Record<string, unknown>;\n const tenancy = def.__tenancy as Record<string, unknown> | undefined;\n return tenancy?.isTenantIdField === true;\n}\n\n/**\n * Extract the `TenantIdFieldOptions` from a field definition.\n *\n * Returns the tenancy-specific options (autoFilter, required, autoPopulate,\n * nullable) stored inside the field descriptor's `__tenancy` property.\n * Returns `null` if the field was not produced by `@tenantId()`.\n *\n * @param field - A raw field definition object, typically from `ObjectRegistry`.\n * @returns The `TenantIdFieldOptions` if the field is a tenant ID field,\n * `null` otherwise.\n *\n * @see isTenantIdField\n * @see TenantIdFieldOptions\n */\nexport function getTenantIdFieldOptions(\n field: unknown,\n): TenantIdFieldOptions | null {\n if (!isTenantIdField(field)) {\n return null;\n }\n const def = field as { __tenancy: TenantIdFieldOptions };\n return def.__tenancy;\n}\n","/**\n * Shared raw-SQL helpers for tenant-scoped collections' \"global\" and\n * \"tenant + globals\" lookups (#1600).\n *\n * Most domain models are `@TenantScoped`. Their collections historically\n * hand-rolled two helpers the OLD way:\n *\n * ```typescript\n * async findGlobal() { return this.list({ where: { tenantId: null } }); }\n * async findWithGlobals(tid) { return this.query(\n * `SELECT * FROM ${this.tableName} WHERE tenant_id = ? OR tenant_id IS NULL`, [tid]); }\n * ```\n *\n * Under an ACTIVE tenant context with tenancy enabled (default\n * `rawQueryPolicy: 'throw'`) BOTH break:\n * - `findGlobal()` routes an explicit `tenant_id IS NULL` filter through\n * `list()`, which the interceptor flags as an isolation violation → throws.\n * - `findWithGlobals()` issues unflagged raw SQL on a tenant-scoped class,\n * which `beforeQuery` blocks → throws.\n * - `findWithGlobals()` also trusts the caller-supplied `tenantId`, so once the\n * raw bypass is added a caller under tenant-A could read tenant-B by passing\n * B's id.\n *\n * These helpers run raw with `{ allowRawOnTenantScoped: true }` (carrying the\n * tenant predicate themselves), and `queryWithGlobals` re-implements the\n * isolation guard the bypass disables (`assertTenantReadAllowed`): a caller\n * under tenant-A must not read tenant-B's rows by passing tenant-B's id. A\n * system / super-admin-bypass context keeps the deliberate cross-tenant\n * capability for admin paths.\n *\n * STI scoping is derived automatically from the collection's item class via\n * `collection.getStiChildMetaType()` (smrt-core), which mirrors the\n * `_meta_type` scoping `list()` applies: STI **child** collections scope the\n * shared table to their own subtype, while STI **base** and CTI collections do\n * not (a base legitimately spans subtypes; CTI tables have no `_meta_type`).\n * Callers never hand-classify their collection. Promoted from\n * `@happyvertical/smrt-messages` (#1596) so every package shares one\n * implementation.\n */\n\nimport type { SmrtCollection, SmrtObject } from '@happyvertical/smrt-core';\nimport {\n getCurrentTenant,\n isSuperAdminBypass,\n TenantIsolationError,\n} from './context.js';\n\n/**\n * Fail closed when an active tenant context requests a different tenant's rows.\n *\n * @param tenantId - The tenant id the caller asked for.\n * @param label - `Class.method` identifier for the error message.\n * @throws {TenantIsolationError} when a non-bypass tenant context is active and\n * does not match `tenantId`.\n */\nexport function assertTenantReadAllowed(tenantId: string, label: string): void {\n const tenantContext = getCurrentTenant();\n if (\n tenantContext &&\n !isSuperAdminBypass() &&\n tenantContext.tenantId !== tenantId\n ) {\n throw new TenantIsolationError(\n `Tenant isolation violation in ${label}: context tenant is ` +\n `'${tenantContext.tenantId}' but query requested '${tenantId}'`,\n { tenantId: tenantContext.tenantId, attemptedTenantId: tenantId },\n );\n }\n}\n\n/**\n * Return all global (tenant-less) rows for a tenant-scoped collection.\n *\n * STI child collections are auto-scoped to their own `_meta_type` (via\n * `collection.getStiChildMetaType()`) so the shared table never returns sibling\n * subtypes; STI base / CTI collections are not scoped.\n *\n * @param collection - The tenant-scoped collection to query.\n */\nexport async function queryGlobal<T, M extends SmrtObject = SmrtObject>(\n collection: SmrtCollection<M>,\n): Promise<T[]> {\n const metaType = collection.getStiChildMetaType();\n const where = metaType\n ? 'WHERE _meta_type = ? AND tenant_id IS NULL'\n : 'WHERE tenant_id IS NULL';\n const params = metaType ? [metaType] : [];\n // Two decoupled type params by design (STI). `M` is inferred from the\n // collection's declared item type — the STI *base* (e.g. `Email`) — and keeps\n // the parameter assignable despite `SmrtCollection`'s contravariant\n // `ModelType` positions. `T` is the caller-declared *row* type: an STI child\n // collection (e.g. `EmailAccountCollection`, statically `SmrtCollection<Email>`)\n // filters by `_meta_type` and hydrates child rows (`EmailAccount`) that differ\n // from `M`. `query()` is statically `M[]` but yields those child instances at\n // runtime, so the bridge cast is required — returning `M[]` would break every\n // STI-child caller.\n return (await collection.query(\n `SELECT * FROM ${collection.tableName} ${where}`,\n params,\n { allowRawOnTenantScoped: true },\n )) as unknown as T[];\n}\n\n/**\n * Return a tenant's rows plus all global rows for a tenant-scoped collection.\n *\n * Fails closed (`assertTenantReadAllowed`) before issuing the bypassed query.\n * STI child collections are auto-scoped to their own `_meta_type` (via\n * `collection.getStiChildMetaType()`); STI base / CTI collections are not.\n *\n * @param collection - The tenant-scoped collection to query.\n * @param tenantId - The tenant id to include alongside globals.\n * @param label - `Class.method` identifier for the isolation error message.\n */\nexport async function queryWithGlobals<T, M extends SmrtObject = SmrtObject>(\n collection: SmrtCollection<M>,\n tenantId: string,\n label: string,\n): Promise<T[]> {\n assertTenantReadAllowed(tenantId, label);\n const metaType = collection.getStiChildMetaType();\n const where = metaType\n ? 'WHERE _meta_type = ? AND (tenant_id = ? OR tenant_id IS NULL)'\n : 'WHERE tenant_id = ? OR tenant_id IS NULL';\n const params = metaType ? [metaType, tenantId] : [tenantId];\n // See `queryGlobal` above: `T` (caller's STI child row type) is intentionally\n // decoupled from `M` (the collection's inferred base type), so the cast\n // bridges `query()`'s static `M[]` to the hydrated child rows.\n return (await collection.query(\n `SELECT * FROM ${collection.tableName} ${where}`,\n params,\n { allowRawOnTenantScoped: true },\n )) as unknown as T[];\n}\n"],"mappings":";;;;;;;;ACgIO,SAAS,aAAa,UAA+B,CAAC,GAAG;CAC9D,QACE,QACA,qBACM;EACN,mCAAmC,QAAQ,gBAAgB;EAE3D,MAAM,YAAY,OAAO;EAYzB,0BAA0B,WAAW;GARnC,MAAM,QAAQ,QAAQ;GACtB,OAAO,QAAQ,SAAS;GACxB,YAAY,QAAQ,cAAc;GAClC,cAAc,QAAQ,gBAAgB;GACtC,uBAAuB,QAAQ,yBAAyB;EAIrB,CAAM;EAG3C,OAAO;CACT;AACF;AA0CO,SAAS,SAAS,UAAgC,CAAC,GAAG;CAC3D,MAAM,OAAO;EACX,YAAY;EACZ,UAAU;EACV,cAAc;EACd,UAAU;EACV,GAAG;CACL;CAEA,SACE,eACA,yBACG;EACH,iCACE,eACA,uBACC,WAAW,gBAAgB;GAC1B,eAAe,uBAAuB,WAAW,aAAa;IAC5D,MAAM;IACN,SAAS;IACT,SAAS;IACT,UAAU,KAAK;IACf,UAAU,KAAK;IACf,WAAW;KACT,GAAG;KACH,iBAAiB;IACnB;GACF,CAAC;EACH,CACF;CACF;AACF;;;ACpIO,SAAS,gBAAgB,OAAyB;CACvD,IAAI,CAAC,SAAS,OAAO,UAAU,UAC7B,OAAO;CAIT,OADgB,MAAI,WACJ,oBAAoB;AACtC;AAgBO,SAAS,wBACd,OAC6B;CAC7B,IAAI,CAAC,gBAAgB,KAAK,GACxB,OAAO;CAGT,OAAO,MAAI;AACb;;;ACrEO,SAAS,wBAAwB,UAAkB,OAAqB;CAC7E,MAAM,gBAAgB,iBAAiB;CACvC,IACE,iBACA,CAAC,mBAAmB,KACpB,cAAc,aAAa,UAE3B,MAAM,IAAI,qBACR,iCAAiC,MAAK,uBAChC,cAAc,SAAQ,yBAA0B,SAAQ,IAC9D;EAAE,UAAU,cAAc;EAAU,mBAAmB;CAAS,CAClE;AAEJ;AAWA,eAAsB,YACpB,YACc;CACd,MAAM,WAAW,WAAW,oBAAoB;CAChD,MAAM,QAAQ,WACV,+CACA;CACJ,MAAM,SAAS,WAAW,CAAC,QAAQ,IAAI,CAAC;CAUxC,OAAQ,MAAM,WAAW,MACvB,iBAAiB,WAAW,UAAS,GAAI,SACzC,QACA,EAAE,wBAAwB,KAAK,CACjC;AACF;AAaA,eAAsB,iBACpB,YACA,UACA,OACc;CACd,wBAAwB,UAAU,KAAK;CACvC,MAAM,WAAW,WAAW,oBAAoB;CAChD,MAAM,QAAQ,WACV,kEACA;CACJ,MAAM,SAAS,WAAW,CAAC,UAAU,QAAQ,IAAI,CAAC,QAAQ;CAI1D,OAAQ,MAAM,WAAW,MACvB,iBAAiB,WAAW,UAAS,GAAI,SACzC,QACA,EAAE,wBAAwB,KAAK,CACjC;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/__smrt-register__.ts","../src/decorators.ts","../src/fields.ts","../src/tenant-global-queries.ts"],"sourcesContent":["/**\n * Self-registers this package's build-time manifest before any @smrt() decorator\n * in the package fires. Fixes issue #1132: in consumer runtimes (tsx, SvelteKit\n * SSR, plain `vite dev`) the decorator's synchronous manifest lookup previously\n * missed because no step populated the global manifest cache — classes got\n * registered with zero fields and `save()` / `toJSON()` silently dropped every\n * declared property.\n *\n * Import this module as the first statement in `src/index.ts` so its top-level\n * side effect runs ahead of any class module's @smrt() decorator.\n *\n * Silent no-op in dev/test, where the vitest plugin already populates manifests\n * via a different path. Only needs to succeed in the published dist output.\n *\n * @see https://github.com/happyvertical/smrt/issues/1132\n */\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\n// During library builds, smrtPlugin replaces this entire module with generated\n// code that embeds the scanned manifest inline (#1506/#1507) — published dists\n// never resolve this URL, so downstream bundlers cannot break registration by\n// relocating the compiled module away from dist/manifest.json. The runtime\n// lookup below is the fallback for source-mode runs without that transform.\nObjectRegistry.registerPackageManifest(\n new URL('./manifest.json', import.meta.url),\n);\n","/**\n * Tenancy Decorators\n *\n * Provides class and property decorators for tenant-scoped SMRT objects.\n *\n * @example\n * ```typescript\n * import { smrt, SmrtObject } from '@happyvertical/smrt-core';\n * import { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\n *\n * @smrt()\n * @TenantScoped({ mode: 'optional' })\n * class Document extends SmrtObject {\n * @tenantId({ nullable: true })\n * tenantId: string | null = null; // null = global document\n *\n * title: string = '';\n * }\n * ```\n *\n * @see https://github.com/happyvertical/smrt/issues/675\n * @see https://github.com/happyvertical/smrt/issues/829\n */\n\nimport {\n applyPendingDecoratorRegistrations,\n type CompatiblePropertyDecorator,\n type CompatiblePropertyDecoratorContext,\n type LegacyPropertyDecoratorTarget,\n ObjectRegistry,\n registerCompatibleFieldDecorator,\n} from '@happyvertical/smrt-core';\nimport type { TenantIdFieldOptions } from './fields.js';\nimport {\n registerTenantScopedConstructor,\n type TenantScopedConfig,\n} from './registry.js';\n\n/**\n * Options accepted by the `@TenantScoped()` class decorator.\n *\n * All fields are optional; defaults match the most restrictive safe behaviour\n * (required mode, auto-filter and auto-populate enabled, no super-admin bypass).\n *\n * @see TenantScoped\n * @see TenantScopedConfig\n */\nexport interface TenantScopedOptions {\n /**\n * Tenancy mode for this class\n * - 'required': Must have tenant context for all operations (default)\n * - 'optional': Works with or without tenant context\n */\n mode?: 'required' | 'optional';\n\n /**\n * Field name containing tenant ID\n * @default 'tenantId'\n */\n field?: string;\n\n /**\n * Auto-filter all queries by tenant\n * @default true\n */\n autoFilter?: boolean;\n\n /**\n * Auto-populate tenant ID from context on create\n * @default true\n */\n autoPopulate?: boolean;\n\n /**\n * Allow super admin bypass for this class\n * @default false - must be explicitly enabled\n */\n allowSuperAdminBypass?: boolean;\n}\n\n/**\n * Mark a class as tenant-scoped\n *\n * This decorator registers the class with the tenancy system so that:\n * - list()/get() queries are automatically filtered by tenant\n * - save() validates tenant ID matches current context\n * - delete() validates tenant ownership\n * - Raw SQL queries trigger policy enforcement\n *\n * @param options - Configuration options\n *\n * @example Basic usage (required tenancy)\n * ```typescript\n * @smrt()\n * @TenantScoped()\n * class Document extends SmrtObject {\n * @tenantId()\n * tenantId: string = '';\n *\n * title: string = '';\n * }\n * ```\n *\n * @example With super admin bypass enabled\n * ```typescript\n * @smrt()\n * @TenantScoped({ allowSuperAdminBypass: true })\n * class AuditLog extends SmrtObject {\n * @tenantId()\n * tenantId: string = '';\n *\n * action: string = '';\n * }\n * ```\n *\n * @example Optional tenancy (works with or without context)\n * ```typescript\n * @smrt()\n * @TenantScoped({ mode: 'optional' })\n * class GlobalConfig extends SmrtObject {\n * @tenantId({ nullable: true })\n * tenantId: string | null = null; // null = global, string = tenant-specific\n *\n * key: string = '';\n * value: string = '';\n * }\n * ```\n */\nexport function TenantScoped(options: TenantScopedOptions = {}) {\n return <T extends Function>(\n target: T,\n decoratorContext?: ClassDecoratorContext,\n ): T => {\n applyPendingDecoratorRegistrations(target, decoratorContext);\n\n // Merge with defaults\n const config: Partial<TenantScopedConfig> = {\n mode: options.mode ?? 'required',\n field: options.field ?? 'tenantId',\n autoFilter: options.autoFilter ?? true,\n autoPopulate: options.autoPopulate ?? true,\n allowSuperAdminBypass: options.allowSuperAdminBypass ?? false,\n };\n\n // Register with the tenancy system\n registerTenantScopedConstructor(target, config);\n\n // Support either class-decorator order. This declaration replaces only a\n // provisional field fallback; explicit @smrt and manifest policy retain\n // their documented precedence.\n ObjectRegistry.reconcileTenantScopedConfig(target, {\n mode: config.mode ?? 'required',\n field: config.field ?? 'tenantId',\n autoFilter: config.autoFilter ?? true,\n autoPopulate: config.autoPopulate ?? true,\n allowSuperAdminBypass: config.allowSuperAdminBypass ?? false,\n });\n\n // Return the class unchanged\n return target;\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Property Decorator: @tenantId\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Tenant ID property decorator\n *\n * Marks a property as the tenant identifier field. This decorator registers\n * the field metadata with ObjectRegistry, keeping the property value clean\n * (no descriptor objects that could be accidentally saved to the database).\n *\n * @param options - Field options (nullable, autoFilter, autoPopulate, etc.)\n * @returns Property decorator\n *\n * @example Basic usage (required tenancy)\n * ```typescript\n * @smrt()\n * @TenantScoped()\n * class Document extends SmrtObject {\n * @tenantId()\n * tenantId: string = '';\n *\n * title: string = '';\n * }\n * ```\n *\n * @example Nullable tenant ID (for global resources)\n * ```typescript\n * @smrt()\n * @TenantScoped({ mode: 'optional' })\n * class GlobalConfig extends SmrtObject {\n * @tenantId({ nullable: true })\n * tenantId: string | null = null; // null = global, string = tenant-specific\n *\n * key: string = '';\n * }\n * ```\n *\n * @see https://github.com/happyvertical/smrt/issues/829 - Why decorators over field helpers\n */\nexport function tenantId(options: TenantIdFieldOptions = {}) {\n const opts = {\n autoFilter: true,\n required: true,\n autoPopulate: true,\n nullable: false,\n ...options,\n };\n\n return ((\n targetOrValue: LegacyPropertyDecoratorTarget | undefined,\n propertyKeyOrContext: CompatiblePropertyDecoratorContext<unknown, unknown>,\n ) => {\n registerCompatibleFieldDecorator(\n targetOrValue,\n propertyKeyOrContext,\n (className, propertyKey, ctor) => {\n const fieldOptions: Parameters<\n typeof ObjectRegistry.registerFieldDecorator\n >[2] = {\n type: 'foreignKey',\n related: 'Tenant',\n sqlType: 'UUID',\n required: opts.required,\n nullable: opts.nullable,\n __tenancy: {\n ...opts,\n isTenantIdField: true,\n },\n };\n ObjectRegistry.registerFieldDecorator(\n className,\n propertyKey,\n fieldOptions,\n ctor,\n );\n },\n );\n }) as CompatiblePropertyDecorator;\n}\n","/**\n * Tenancy Field Types and Utilities\n *\n * This module provides types and utility functions for tenant ID fields.\n * The actual field decorator is in decorators.ts.\n *\n * @see https://github.com/happyvertical/smrt/issues/675\n * @see https://github.com/happyvertical/smrt/issues/829\n */\n\n/**\n * Options for the `@tenantId()` property decorator.\n *\n * Controls how the decorated field interacts with the tenancy interceptor.\n * All options default to the strictest safe values: auto-filter on, required,\n * auto-populate on, not nullable.\n *\n * @see tenantId\n * @see TenantScopedOptions\n */\nexport interface TenantIdFieldOptions {\n /**\n * Auto-filter queries by this field\n * @default true\n */\n autoFilter?: boolean;\n\n /**\n * Require this field to have a value on save\n * @default true\n */\n required?: boolean;\n\n /**\n * Auto-populate from context on create if not set\n * @default true\n */\n autoPopulate?: boolean;\n\n /**\n * Allow null values (for global resources)\n * @default false\n */\n nullable?: boolean;\n}\n\n// Symbol to identify tenantId fields\nexport const TENANT_ID_SYMBOL = Symbol('tenantId');\n\n/**\n * Internal field descriptor stored in `ObjectRegistry` when `@tenantId()` is\n * applied to a property.\n *\n * Consumers should use `isTenantIdField()` and `getTenantIdFieldOptions()`\n * to inspect these descriptors rather than reading the raw properties directly.\n *\n * @see isTenantIdField\n * @see getTenantIdFieldOptions\n */\nexport interface TenantIdFieldDefinition {\n /** Field type marker */\n type: 'foreignKey';\n /** Reference to Tenant class (placeholder - actual class resolved at runtime) */\n reference: 'Tenant';\n /** SQL type */\n sqlType: 'UUID';\n /** Field is required */\n required: boolean;\n /** Field allows null */\n nullable: boolean;\n /** Tenancy-specific options */\n __tenancy: TenantIdFieldOptions & { isTenantIdField: true };\n}\n\n/**\n * Return `true` if the given field definition was produced by the `@tenantId()`\n * decorator (i.e., it has an `__tenancy.isTenantIdField` marker).\n *\n * Used internally by the interceptor and code generators to locate the tenant\n * ID field on a class without knowing its property name in advance.\n *\n * @param field - A raw field definition object, typically from `ObjectRegistry`.\n * @returns `true` if `field` is a tenant ID field definition, `false` otherwise.\n *\n * @example\n * ```typescript\n * const fields = ObjectRegistry.getFields('Document');\n * const tenantField = Object.entries(fields).find(([, def]) => isTenantIdField(def));\n * ```\n *\n * @see getTenantIdFieldOptions\n * @see TenantIdFieldDefinition\n */\nexport function isTenantIdField(field: unknown): boolean {\n if (!field || typeof field !== 'object') {\n return false;\n }\n const def = field as Record<string, unknown>;\n const tenancy = def.__tenancy as Record<string, unknown> | undefined;\n return tenancy?.isTenantIdField === true;\n}\n\n/**\n * Extract the `TenantIdFieldOptions` from a field definition.\n *\n * Returns the tenancy-specific options (autoFilter, required, autoPopulate,\n * nullable) stored inside the field descriptor's `__tenancy` property.\n * Returns `null` if the field was not produced by `@tenantId()`.\n *\n * @param field - A raw field definition object, typically from `ObjectRegistry`.\n * @returns The `TenantIdFieldOptions` if the field is a tenant ID field,\n * `null` otherwise.\n *\n * @see isTenantIdField\n * @see TenantIdFieldOptions\n */\nexport function getTenantIdFieldOptions(\n field: unknown,\n): TenantIdFieldOptions | null {\n if (!isTenantIdField(field)) {\n return null;\n }\n const def = field as { __tenancy: TenantIdFieldOptions };\n return def.__tenancy;\n}\n","/**\n * Shared raw-SQL helpers for tenant-scoped collections' \"global\" and\n * \"tenant + globals\" lookups (#1600).\n *\n * Most domain models are `@TenantScoped`. Their collections historically\n * hand-rolled two helpers the OLD way:\n *\n * ```typescript\n * async findGlobal() { return this.list({ where: { tenantId: null } }); }\n * async findWithGlobals(tid) { return this.query(\n * `SELECT * FROM ${this.tableName} WHERE tenant_id = ? OR tenant_id IS NULL`, [tid]); }\n * ```\n *\n * Under an ACTIVE tenant context with tenancy enabled (default\n * `rawQueryPolicy: 'throw'`) BOTH break:\n * - `findGlobal()` routes an explicit `tenant_id IS NULL` filter through\n * `list()`, which the interceptor flags as an isolation violation → throws.\n * - `findWithGlobals()` issues unflagged raw SQL on a tenant-scoped class,\n * which `beforeQuery` blocks → throws.\n * - `findWithGlobals()` also trusts the caller-supplied `tenantId`, so once the\n * raw bypass is added a caller under tenant-A could read tenant-B by passing\n * B's id.\n *\n * These helpers run raw with `{ allowRawOnTenantScoped: true }` (carrying the\n * tenant predicate themselves), and `queryWithGlobals` re-implements the\n * isolation guard the bypass disables (`assertTenantReadAllowed`): a caller\n * under tenant-A must not read tenant-B's rows by passing tenant-B's id. A\n * system / super-admin-bypass context keeps the deliberate cross-tenant\n * capability for admin paths.\n *\n * STI scoping is derived automatically from the collection's item class via\n * `collection.getStiChildMetaType()` (smrt-core), which mirrors the\n * `_meta_type` scoping `list()` applies: STI **child** collections scope the\n * shared table to their own subtype, while STI **base** and CTI collections do\n * not (a base legitimately spans subtypes; CTI tables have no `_meta_type`).\n * Callers never hand-classify their collection. Promoted from\n * `@happyvertical/smrt-messages` (#1596) so every package shares one\n * implementation.\n */\n\nimport type { SmrtCollection, SmrtObject } from '@happyvertical/smrt-core';\nimport {\n getCurrentTenant,\n isSuperAdminBypass,\n TenantIsolationError,\n} from './context.js';\n\n/**\n * Fail closed when an active tenant context requests a different tenant's rows.\n *\n * @param tenantId - The tenant id the caller asked for.\n * @param label - `Class.method` identifier for the error message.\n * @throws {TenantIsolationError} when a non-bypass tenant context is active and\n * does not match `tenantId`.\n */\nexport function assertTenantReadAllowed(tenantId: string, label: string): void {\n const tenantContext = getCurrentTenant();\n if (\n tenantContext &&\n !isSuperAdminBypass() &&\n tenantContext.tenantId !== tenantId\n ) {\n throw new TenantIsolationError(\n `Tenant isolation violation in ${label}: context tenant is ` +\n `'${tenantContext.tenantId}' but query requested '${tenantId}'`,\n { tenantId: tenantContext.tenantId, attemptedTenantId: tenantId },\n );\n }\n}\n\n/**\n * Return all global (tenant-less) rows for a tenant-scoped collection.\n *\n * STI child collections are auto-scoped to their own `_meta_type` (via\n * `collection.getStiChildMetaType()`) so the shared table never returns sibling\n * subtypes; STI base / CTI collections are not scoped.\n *\n * @param collection - The tenant-scoped collection to query.\n */\nexport async function queryGlobal<T, M extends SmrtObject = SmrtObject>(\n collection: SmrtCollection<M>,\n): Promise<T[]> {\n const metaType = collection.getStiChildMetaType();\n const where = metaType\n ? 'WHERE _meta_type = ? AND tenant_id IS NULL'\n : 'WHERE tenant_id IS NULL';\n const params = metaType ? [metaType] : [];\n // Two decoupled type params by design (STI). `M` is inferred from the\n // collection's declared item type — the STI *base* (e.g. `Email`) — and keeps\n // the parameter assignable despite `SmrtCollection`'s contravariant\n // `ModelType` positions. `T` is the caller-declared *row* type: an STI child\n // collection (e.g. `EmailAccountCollection`, statically `SmrtCollection<Email>`)\n // filters by `_meta_type` and hydrates child rows (`EmailAccount`) that differ\n // from `M`. `query()` is statically `M[]` but yields those child instances at\n // runtime, so the bridge cast is required — returning `M[]` would break every\n // STI-child caller.\n return (await collection.query(\n `SELECT * FROM ${collection.tableName} ${where}`,\n params,\n { allowRawOnTenantScoped: true },\n )) as unknown as T[];\n}\n\n/**\n * Return a tenant's rows plus all global rows for a tenant-scoped collection.\n *\n * Fails closed (`assertTenantReadAllowed`) before issuing the bypassed query.\n * STI child collections are auto-scoped to their own `_meta_type` (via\n * `collection.getStiChildMetaType()`); STI base / CTI collections are not.\n *\n * @param collection - The tenant-scoped collection to query.\n * @param tenantId - The tenant id to include alongside globals.\n * @param label - `Class.method` identifier for the isolation error message.\n */\nexport async function queryWithGlobals<T, M extends SmrtObject = SmrtObject>(\n collection: SmrtCollection<M>,\n tenantId: string,\n label: string,\n): Promise<T[]> {\n assertTenantReadAllowed(tenantId, label);\n const metaType = collection.getStiChildMetaType();\n const where = metaType\n ? 'WHERE _meta_type = ? AND (tenant_id = ? OR tenant_id IS NULL)'\n : 'WHERE tenant_id = ? OR tenant_id IS NULL';\n const params = metaType ? [metaType, tenantId] : [tenantId];\n // See `queryGlobal` above: `T` (caller's STI child row type) is intentionally\n // decoupled from `M` (the collection's inferred base type), so the cast\n // bridges `query()`'s static `M[]` to the hydrated child rows.\n return (await collection.query(\n `SELECT * FROM ${collection.tableName} ${where}`,\n params,\n { allowRawOnTenantScoped: true },\n )) as unknown as T[];\n}\n"],"mappings":";;;;;;;;ACgIO,SAAS,aAAa,UAA+B,CAAC,GAAG;CAC9D,QACE,QACA,qBACM;EACN,mCAAmC,QAAQ,gBAAgB;EAG3D,MAAM,SAAsC;GAC1C,MAAM,QAAQ,QAAQ;GACtB,OAAO,QAAQ,SAAS;GACxB,YAAY,QAAQ,cAAc;GAClC,cAAc,QAAQ,gBAAgB;GACtC,uBAAuB,QAAQ,yBAAyB;EAC1D;EAGA,gCAAgC,QAAQ,MAAM;EAK9C,eAAe,4BAA4B,QAAQ;GACjD,MAAM,OAAO,QAAQ;GACrB,OAAO,OAAO,SAAS;GACvB,YAAY,OAAO,cAAc;GACjC,cAAc,OAAO,gBAAgB;GACrC,uBAAuB,OAAO,yBAAyB;EACzD,CAAC;EAGD,OAAO;CACT;AACF;AA0CO,SAAS,SAAS,UAAgC,CAAC,GAAG;CAC3D,MAAM,OAAO;EACX,YAAY;EACZ,UAAU;EACV,cAAc;EACd,UAAU;EACV,GAAG;CACL;CAEA,SACE,eACA,yBACG;EACH,iCACE,eACA,uBACC,WAAW,aAAa,SAAS;GAChC,MAAM,eAEC;IACL,MAAM;IACN,SAAS;IACT,SAAS;IACT,UAAU,KAAK;IACf,UAAU,KAAK;IACf,WAAW;KACT,GAAG;KACH,iBAAiB;IACnB;GACF;GACA,eAAe,uBACb,WACA,aACA,cACA,IACF;EACF,CACF;CACF;AACF;;;ACrJO,SAAS,gBAAgB,OAAyB;CACvD,IAAI,CAAC,SAAS,OAAO,UAAU,UAC7B,OAAO;CAIT,OADgB,MAAI,WACJ,oBAAoB;AACtC;AAgBO,SAAS,wBACd,OAC6B;CAC7B,IAAI,CAAC,gBAAgB,KAAK,GACxB,OAAO;CAGT,OAAO,MAAI;AACb;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kB,KACxB,IAAI,CAAC;IAEV;;OAEG;IACH,oBAAoB,CAAC,EAAE,CACrB,SAAS,EAAE,MAAM,EACjB,gBAAgB,EAAE,MAAM,EACxB,cAAc,EAAE,MAAM,EACtB,OAAO,EAAE,kBAAkB,KACxB,IAAI,CAAC;IAEV;;;;OAIG;IACH,WAAW,CAAC,EAAE,WAAW,CAAC;IAE1B;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;CAC7B;AAuDD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,GAAE,wBAA6B,GACrC,qBAAqB,CA4dvB;AAWD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,aAAa,CAAC,OAAO,GAAE,wBAA6B,GAAG,IAAI,CA+B1E;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,cAAc,IAAI,IAAI,CAgBrC;AAED;;;;;;;;;GASG;AACH,OAAO,EAAE,gBAAgB,EAAE,CAAC"}
|
package/dist/manifest.json
CHANGED
package/dist/registry.d.ts
CHANGED
|
@@ -51,17 +51,27 @@ export interface TenantScopedConfig {
|
|
|
51
51
|
*/
|
|
52
52
|
allowSuperAdminBypass: boolean;
|
|
53
53
|
}
|
|
54
|
+
/** @internal Used by TenantScoped; direct callers must use the string API. */
|
|
55
|
+
export declare function registerTenantScopedConstructor(target: Function, config?: Partial<TenantScopedConfig>): void;
|
|
54
56
|
/**
|
|
55
57
|
* Register a class as tenant-scoped with the given configuration.
|
|
56
58
|
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
59
|
+
* Call this directly when you cannot use decorators (e.g., third-party classes
|
|
60
|
+
* or plain objects in tests). Defaults from `DEFAULT_CONFIG` are merged over
|
|
61
|
+
* any omitted options. `@TenantScoped()` has its own constructor-aware mirror
|
|
62
|
+
* and reconciles its authoritative policy in core.
|
|
63
|
+
*
|
|
64
|
+
* A simple selector binds to its exact core constructor when one owner is
|
|
65
|
+
* uniquely resolvable, including when registration happens before core. Once
|
|
66
|
+
* bound it remains attached to that constructor if a same-name peer appears.
|
|
67
|
+
* If core clears that constructor and reuses its qualified name, the selector
|
|
68
|
+
* fails closed until the caller explicitly unregisters and re-registers it.
|
|
69
|
+
* If ownership is ambiguous before binding, interception fails closed until a
|
|
70
|
+
* caller registers an explicit qualified selector. Calling this again for the
|
|
71
|
+
* same selector overwrites that selector's previous entry.
|
|
72
|
+
*
|
|
73
|
+
* @param className - A simple class name (e.g., `'Document'`) or exact core
|
|
74
|
+
* qualified name (e.g., `'@package/name:Document'`).
|
|
65
75
|
* @param config - Partial tenancy configuration; omitted fields receive defaults.
|
|
66
76
|
*
|
|
67
77
|
* @example
|
package/dist/registry.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH;;;;;;;;GAQG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;;;OAKG;IACH,IAAI,EAAE,UAAU,GAAG,UAAU,CAAC;IAE9B;;;OAGG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;;OAGG;IACH,UAAU,EAAE,OAAO,CAAC;IAEpB;;;OAGG;IACH,YAAY,EAAE,OAAO,CAAC;IAEtB;;;OAGG;IACH,qBAAqB,EAAE,OAAO,CAAC;CAChC;
|
|
1
|
+
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH;;;;;;;;GAQG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;;;OAKG;IACH,IAAI,EAAE,UAAU,GAAG,UAAU,CAAC;IAE9B;;;OAGG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;;OAGG;IACH,UAAU,EAAE,OAAO,CAAC;IAEpB;;;OAGG;IACH,YAAY,EAAE,OAAO,CAAC;IAEtB;;;OAGG;IACH,qBAAqB,EAAE,OAAO,CAAC;CAChC;AAmFD,8EAA8E;AAC9E,wBAAgB,+BAA+B,CAC7C,MAAM,EAAE,QAAQ,EAChB,MAAM,GAAE,OAAO,CAAC,kBAAkB,CAAM,GACvC,IAAI,CAIN;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAgB,yBAAyB,CACvC,SAAS,EAAE,MAAM,EACjB,MAAM,GAAE,OAAO,CAAC,kBAAkB,CAAM,GACvC,IAAI,CAkBN;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,2BAA2B,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAUnE;AA0KD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,qBAAqB,CACnC,SAAS,EAAE,MAAM,GAChB,kBAAkB,GAAG,SAAS,CAQhC;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAE9D;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,yBAAyB,IAAI,GAAG,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAE3E;AAED;;;;;;;;GAQG;AACH,wBAAgB,yBAAyB,IAAI,IAAI,CAMhD"}
|
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,13 +3,13 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-tenancy",
|
|
6
|
-
"packageVersion": "0.
|
|
6
|
+
"packageVersion": "0.49.0",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
12
|
-
"agents": "
|
|
10
|
+
"manifest": "3b815990bf8afc7431bdb67cad61d157cf492f103b91027a9553e4b0282cc590",
|
|
11
|
+
"packageJson": "7597edf2685876ed4fc24081f68a67ddb37f805d762a86a70f4d837e4610484e",
|
|
12
|
+
"agents": "b4494fbdca37281d8557810a757c8a6abca8527fbee2785ec1e19adf0ce10a8a"
|
|
13
13
|
},
|
|
14
14
|
"exports": [
|
|
15
15
|
".",
|
|
@@ -62,5 +62,5 @@
|
|
|
62
62
|
"polymorphicAssociations": 0,
|
|
63
63
|
"uuidColumns": 0
|
|
64
64
|
},
|
|
65
|
-
"agentDoc": "# @happyvertical/smrt-tenancy\n\nMulti-tenancy via AsyncLocalStorage context propagation with automatic query filtering and tenant ID population.\n\n## Context Propagation\n\n```typescript\nimport { withTenant, getTenantId, withSystemContext } from '@happyvertical/smrt-tenancy';\n\nawait withTenant({ tenantId: 'tenant-123' }, async () => {\n // All SmrtCollection queries auto-filtered by tenantId\n // All creates auto-populate tenantId\n const docs = await collection.list({}); // WHERE tenant_id = 'tenant-123'\n});\n\nawait withSystemContext(async () => { /* bypasses all tenant checks */ });\n```\n\n**Critical distinction**: `withSystemContext()` sets a SYSTEM_CONTEXT_MARKER sentinel — different from \"no context\" (undefined). Interceptor can distinguish intentional bypass from missing context.\n\n**Duplication-safe storage**: the underlying `AsyncLocalStorage` is a `Symbol.for`-keyed singleton on `globalThis`, so context survives Vite/vitest/SvelteKit pipelines that evaluate the module more than once — context entered through one module instance is visible to guards in another (#2077).\n\n## Interceptor System\n\nHooks into SmrtCollection via `GlobalInterceptors.register()` (priority 100, runs first):\n\n| Hook | Behavior |\n|------|----------|\n| `beforeList` | Injects `tenantId` into WHERE clause; validates existing filters match context |\n| `beforeGet` | Same — resolves string lookups via core's `resolveGetStringFilter()` (UUID → `{ id }`, else `{ slug, context: '' }`) and adds the tenant predicate (#2365) |\n| `beforeSave` | Auto-populates tenantId if empty + `autoPopulate: true`; validates if already set |\n| `beforeDelete` | Validates instance.tenantId matches context |\n| `beforeQuery` | Enforces raw SQL policy on tenant-scoped classes (`throw`/`warn`/`allow`) |\n| `afterSave` | Emits `directory.<class>.created`/`updated` via `dispatchBus` for configured `directoryClasses` |\n| `afterDelete` | Emits `directory.<class>.deleted` via `dispatchBus` for configured `directoryClasses` |\n\nMismatches throw `TenantIsolationError`. Missing required context throws `TenantContextError`.\n\n**Optional-mode reads with no context pass through UNFILTERED at the interceptor.** That is intentional for trusted/admin call paths, but it means the interceptor alone does not protect a tenant-scoped model exposed as `@smrt({ api: { public } })`: an anonymous HTTP read has no context, so the interceptor would return every tenant's rows. The generated REST + SvelteKit read routes close this by injecting a `{ tenantId: null }` filter when tenancy is enabled but no context is active, so public/anonymous reads fail closed to **global (NULL-tenant) rows only** — mirroring the dispatch resolver's *enforced, no active tenant → global rows only* rule (#1782). Authenticated reads still scope to the caller's tenant via the interceptor.\n\n## Read-Path Coverage (#2365)\n\nTenant scoping is a whole-path property — every read path is interceptor-aware,\nnot only collection list/get:\n\n- **Get-by-slug**: `collection.get('<slug>')` works under a tenant context. The\n interceptor resolves string filters with core's `resolveGetStringFilter()`\n instead of assuming they are ids. Any custom `beforeGet` interceptor that\n rewrites a string filter must do the same.\n- **Hydration and identity**: `new Model({ id | slug }).initialize()`,\n `loadFromId()`, `loadFromSlug()`, `getSavedId()` and `getId()` run their\n filters through the `beforeGet` pipeline, so constructor hydration cannot\n read another tenant's row and `getId()` can never adopt another tenant's\n same-slug row id (which would steer a later `save()` onto the foreign row).\n Required-mode classes fail closed (`TenantContextError`) when hydrated\n outside a tenant context; `withSystemContext()` / super-admin bypass remain\n the explicit cross-tenant paths.\n- **Vector search**: `semanticSearch()` / `findSimilarToEmbedding()` restrict\n candidates to the tenant's rows BEFORE top-K ranking (the tenant predicate is\n resolved through the `beforeList` pipeline), so results are never starved by\n — and similarity ranks never leak — other tenants' content.\n- **Collection memory**: `remember()`/`recall()`/`recallAll()`/`forget()` on a\n tenant-scoped collection key `_smrt_contexts.owner_id` per tenant\n (`__collection__:<tenantId>`) under an active tenant context. Isolation is\n strict: tenant-keyed memory never falls back to the shared `__collection__`\n key, and memory learned outside a tenant context is invisible inside one.\n Two edge semantics to know: under `withSuperAdminBypass()` reads skip\n filtering but memory still keys to the active tenant (scoped tighter, not a\n leak), and an empty-string tenant id resolves to the shared key (an\n empty-string tenant is a misconfiguration — real tenant ids are uuids).\n\n## Registration — Two Patterns\n\n```typescript\n// Pattern 1: Tenancy decorator\n@TenantScoped({ mode: 'optional' })\nclass Doc extends SmrtObject { @tenantId({ nullable: true }) tenantId: string | null = null; }\n\n// Pattern 2: Core decorator (tenancy package reads this too)\n@smrt({ tenantScoped: { mode: 'optional' } })\nclass Doc extends SmrtObject { tenantId: string | null = null; }\n```\n\nModes: `'required'` (default — throws without context) or `'optional'` (passes through if no context).\n\n## Adapters\n\n- **Express**: `createExpressMiddleware()` — uses `enterTenantContext()` (not withTenant, because middleware returns before handlers run)\n- **SvelteKit**: `createSvelteKitHandle()` — stores context in `event.locals`\n- **CLI**: `createCliContext()` — `run()`, `runWithTenant()`, `runAsSystem()`, `runAsSuperAdmin()`\n\n## Super Admin Bypass\n\n`withSuperAdminBypass()` keeps tenant context but disables auto-filtering. Different from `withSystemContext()` which removes context entirely.\n\n## Gotchas\n\n- **Context lost in callbacks**: `setTimeout(() => getTenantId(), 100)` → undefined. Fix: `TenantContext.bind(fn)`\n- **Nested contexts override**: inner `withTenant()` overrides outer; restores on exit\n- **Auto-populate only if empty**: if tenantId already set, interceptor validates (not overwrites)\n- **Isolation checked at query time**: `list({ where: { tenantId: 'other' } })` throws immediately\n- **Testing**: `resetTenancy()` + `setupTestTenancy()` in beforeEach; `testTenantIsolation()` helper\n- **Natural keys are per tenant (smrt#2360)**: a tenant-scoped class with no explicit `conflictColumns` upserts on, and indexes, `(tenant_id, slug, context[, _meta_type])` — `save()` from tenant B with tenant A's slug is a second row, never an overwrite; within a tenant the natural key still dedups; NULL-tenant (`optional` mode, no context) rows dedup among themselves through the SDK's null-aware upsert but not through the index (NULLs are distinct), so raw SQL `ON CONFLICT (slug, context…)` on such a table no longer binds — use `WHERE NOT EXISTS`, and on PostgreSQL an advisory lock, as `ProfileTypeCollection.getOrCreateGlobalBySlug()` does. Core
|
|
65
|
+
"agentDoc": "# @happyvertical/smrt-tenancy\n\nMulti-tenancy via AsyncLocalStorage context propagation with automatic query filtering and tenant ID population.\n\n## Context Propagation\n\n```typescript\nimport { withTenant, getTenantId, withSystemContext } from '@happyvertical/smrt-tenancy';\n\nawait withTenant({ tenantId: 'tenant-123' }, async () => {\n // All SmrtCollection queries auto-filtered by tenantId\n // All creates auto-populate tenantId\n const docs = await collection.list({}); // WHERE tenant_id = 'tenant-123'\n});\n\nawait withSystemContext(async () => { /* bypasses all tenant checks */ });\n```\n\n**Critical distinction**: `withSystemContext()` sets a SYSTEM_CONTEXT_MARKER sentinel — different from \"no context\" (undefined). Interceptor can distinguish intentional bypass from missing context.\n\n**Duplication-safe storage**: the underlying `AsyncLocalStorage` is a `Symbol.for`-keyed singleton on `globalThis`, so context survives Vite/vitest/SvelteKit pipelines that evaluate the module more than once — context entered through one module instance is visible to guards in another (#2077).\n\n## Interceptor System\n\nHooks into SmrtCollection via `GlobalInterceptors.register()` (priority 100, runs first):\n\n| Hook | Behavior |\n|------|----------|\n| `beforeList` | Injects `tenantId` into WHERE clause; validates existing filters match context |\n| `beforeGet` | Same — resolves string lookups via core's `resolveGetStringFilter()` (UUID → `{ id }`, else `{ slug, context: '' }`) and adds the tenant predicate (#2365) |\n| `beforeSave` | Auto-populates tenantId if empty + `autoPopulate: true`; validates if already set |\n| `beforeDelete` | Validates instance.tenantId matches context |\n| `beforeQuery` | Enforces raw SQL policy on tenant-scoped classes (`throw`/`warn`/`allow`) |\n| `afterSave` | Emits `directory.<class>.created`/`updated` via `dispatchBus` for configured `directoryClasses` |\n| `afterDelete` | Emits `directory.<class>.deleted` via `dispatchBus` for configured `directoryClasses` |\n\nMismatches throw `TenantIsolationError`. Missing required context throws `TenantContextError`.\n\n**Optional-mode reads with no context pass through UNFILTERED at the interceptor.** That is intentional for trusted/admin call paths, but it means the interceptor alone does not protect a tenant-scoped model exposed as `@smrt({ api: { public } })`: an anonymous HTTP read has no context, so the interceptor would return every tenant's rows. The generated REST + SvelteKit read routes close this by injecting a `{ tenantId: null }` filter when tenancy is enabled but no context is active, so public/anonymous reads fail closed to **global (NULL-tenant) rows only** — mirroring the dispatch resolver's *enforced, no active tenant → global rows only* rule (#1782). Authenticated reads still scope to the caller's tenant via the interceptor.\n\n## Read-Path Coverage (#2365)\n\nTenant scoping is a whole-path property — every read path is interceptor-aware,\nnot only collection list/get:\n\n- **Get-by-slug**: `collection.get('<slug>')` works under a tenant context. The\n interceptor resolves string filters with core's `resolveGetStringFilter()`\n instead of assuming they are ids. Any custom `beforeGet` interceptor that\n rewrites a string filter must do the same.\n- **Hydration and identity**: `new Model({ id | slug }).initialize()`,\n `loadFromId()`, `loadFromSlug()`, `getSavedId()` and `getId()` run their\n filters through the `beforeGet` pipeline, so constructor hydration cannot\n read another tenant's row and `getId()` can never adopt another tenant's\n same-slug row id (which would steer a later `save()` onto the foreign row).\n Required-mode classes fail closed (`TenantContextError`) when hydrated\n outside a tenant context; `withSystemContext()` / super-admin bypass remain\n the explicit cross-tenant paths.\n- **Vector search**: `semanticSearch()` / `findSimilarToEmbedding()` restrict\n candidates to the tenant's rows BEFORE top-K ranking (the tenant predicate is\n resolved through the `beforeList` pipeline), so results are never starved by\n — and similarity ranks never leak — other tenants' content.\n- **Collection memory**: `remember()`/`recall()`/`recallAll()`/`forget()` on a\n tenant-scoped collection key `_smrt_contexts.owner_id` per tenant\n (`__collection__:<tenantId>`) under an active tenant context. Isolation is\n strict: tenant-keyed memory never falls back to the shared `__collection__`\n key, and memory learned outside a tenant context is invisible inside one.\n Two edge semantics to know: under `withSuperAdminBypass()` reads skip\n filtering but memory still keys to the active tenant (scoped tighter, not a\n leak), and an empty-string tenant id resolves to the shared key (an\n empty-string tenant is a misconfiguration — real tenant ids are uuids).\n\n## Registration — Two Patterns\n\n```typescript\n// Pattern 1: Tenancy decorator\n@TenantScoped({ mode: 'optional' })\nclass Doc extends SmrtObject { @tenantId({ nullable: true }) tenantId: string | null = null; }\n\n// Pattern 2: Core decorator (tenancy package reads this too)\n@smrt({ tenantScoped: { mode: 'optional' } })\nclass Doc extends SmrtObject { tenantId: string | null = null; }\n```\n\nThe exported `registerTenantScopedClass()` also accepts a simple or qualified\nstring selector for third-party classes and test doubles. A simple selector is\nbound to the one exact core constructor when that name is uniquely resolvable;\nit may be registered before core. Once bound, a later same-name package peer\ndoes not inherit its policy. If two core classes exist before the simple\nselector can bind, operations fail closed until the caller registers an exact\nqualified name (for example, `@package/name:Doc`). No lookup strips a namespace\nto guess an owner. If core clears a bound constructor and reuses its qualified\nname, unregister and register the selector again; it will not silently transfer\npolicy to the replacement constructor.\n\nModes: `'required'` (default — throws without context) or `'optional'` (passes through if no context).\n\n## Adapters\n\n- **Express**: `createExpressMiddleware()` — uses `enterTenantContext()` (not withTenant, because middleware returns before handlers run)\n- **SvelteKit**: `createSvelteKitHandle()` — stores context in `event.locals`\n- **CLI**: `createCliContext()` — `run()`, `runWithTenant()`, `runAsSystem()`, `runAsSuperAdmin()`\n\n## Super Admin Bypass\n\n`withSuperAdminBypass()` keeps tenant context but disables auto-filtering. Different from `withSystemContext()` which removes context entirely.\n\n## Gotchas\n\n- **Context lost in callbacks**: `setTimeout(() => getTenantId(), 100)` → undefined. Fix: `TenantContext.bind(fn)`\n- **Nested contexts override**: inner `withTenant()` overrides outer; restores on exit\n- **Auto-populate only if empty**: if tenantId already set, interceptor validates (not overwrites)\n- **Isolation checked at query time**: `list({ where: { tenantId: 'other' } })` throws immediately\n- **Testing**: `resetTenancy()` + `setupTestTenancy()` in beforeEach; `testTenantIsolation()` helper\n- **Natural keys are per tenant (smrt#2360)**: a tenant-scoped class with no explicit `conflictColumns` upserts on, and indexes, `(tenant_id, slug, context[, _meta_type])` — `save()` from tenant B with tenant A's slug is a second row, never an overwrite; within a tenant the natural key still dedups; NULL-tenant (`optional` mode, no context) rows dedup among themselves through the SDK's null-aware upsert but not through the index (NULLs are distinct), so raw SQL `ON CONFLICT (slug, context…)` on such a table no longer binds — use `WHERE NOT EXISTS`, and on PostgreSQL an advisory lock, as `ProfileTypeCollection.getOrCreateGlobalBySlug()` does. Core resolves tenant schema policy in order: explicit `@smrt`, manifest (including an omitted `tenantScoped`), exact-constructor `@TenantScoped()` reconciliation, then marked-field fallback; it never reads the standalone tenancy registry. This keeps schema and upsert behavior aligned before `enableTenancy()` runs. Rollout: deploy the code and `smrt db:migrate` together (neither version's create works against the other's index), and backfill `tenant_id` on legacy NULL-tenant rows first — a tenant-context save no longer adopts a `(NULL, slug)` row, it inserts beside it and that tenant stops seeing the legacy one (details in `packages/core/agents/schema-paths.md`).\n- **Manifest/runtime mismatch fails closed (smrt#2763)**: if a cached manifest omits or sets `tenantScoped: false` while the exact runtime constructor carries `@TenantScoped()`, registration is rejected; regenerate the manifest. A rejected late manifest or conflicting promotion preserves a previously valid scoped registration. Applying `@TenantScoped()` to an already-global manifest registration that omits or disables tenancy instead marks that class unavailable to conflict-key, schema, and tenancy interceptor operations until a corrected manifest explicitly declares tenancy. This prevents a global unique key from conflicting with tenant-enforced reads or writes.\n\n## Known exceptions to monorepo standards\n\n- **`serializeInstance()` in `src/interceptor.ts` calls `instance.toJSON()` directly** (standards.md §7 forbids this in favor of `transformJSON()`). The interceptor must serialize arbitrary instances handed to it — including workspace stubs and plain-object test doubles whose classes may not extend `SmrtObject` and therefore have no `transformJSON()` hook. The call is duck-typed and falls back to manual key iteration when `toJSON` is absent. See the inline comment at the call site for the full rationale.\n"
|
|
66
66
|
}
|
package/dist/testing.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as setupTestTenancy, i as resetTenancy, n as assertTenantIsolationViolation, o as testTenantIsolation, r as createTestTenantContext, t as assertTenantContextRequired } from "./chunks/testing-
|
|
1
|
+
import { a as setupTestTenancy, i as resetTenancy, n as assertTenantIsolationViolation, o as testTenantIsolation, r as createTestTenantContext, t as assertTenantContextRequired } from "./chunks/testing-CrMnRY8M.js";
|
|
2
2
|
export { assertTenantContextRequired, assertTenantIsolationViolation, createTestTenantContext, resetTenancy, setupTestTenancy, testTenantIsolation };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@happyvertical/smrt-tenancy",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.49.0",
|
|
4
4
|
"smrtJsdoc": "strict",
|
|
5
5
|
"description": "Production-ready multi-tenancy framework for SMRT with automatic tenant isolation and enforcement",
|
|
6
6
|
"type": "module",
|
|
@@ -43,9 +43,9 @@
|
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
45
|
"@happyvertical/logger": "^0.89.6",
|
|
46
|
-
"@happyvertical/smrt-core": "0.
|
|
47
|
-
"@happyvertical/smrt-types": "0.
|
|
48
|
-
"@happyvertical/smrt-ui": "0.
|
|
46
|
+
"@happyvertical/smrt-core": "0.49.0",
|
|
47
|
+
"@happyvertical/smrt-types": "0.49.0",
|
|
48
|
+
"@happyvertical/smrt-ui": "0.49.0",
|
|
49
49
|
"@happyvertical/sql": "^0.89.6",
|
|
50
50
|
"@happyvertical/utils": "^0.89.6"
|
|
51
51
|
},
|
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
}
|
|
59
59
|
},
|
|
60
60
|
"devDependencies": {
|
|
61
|
-
"@happyvertical/smrt-vitest": "0.
|
|
61
|
+
"@happyvertical/smrt-vitest": "0.49.0",
|
|
62
62
|
"@sveltejs/package": "^2.5.8",
|
|
63
63
|
"@sveltejs/vite-plugin-svelte": "^7.1.2",
|
|
64
64
|
"@types/node": "24.13.2",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"testing-Cow9qCBw.js","names":[],"sources":["../../src/registry.ts","../../src/enabled-state.ts","../../src/entry-point.ts","../../src/interceptor.ts","../../src/testing.ts"],"sourcesContent":["/**\n * Tenant-Scoped Class Registry\n *\n * Tracks which classes are tenant-scoped and their configuration.\n * Used by the interceptor to determine how to handle operations.\n *\n * This registry supports two patterns:\n * 1. @TenantScoped() decorator + tenantId field (original pattern)\n * 2. @smrt({ tenantScoped: true }) in smrt-core (Issue #688 pattern)\n *\n * Both patterns are automatically recognized by the interceptor.\n *\n * @see https://github.com/happyvertical/smrt/issues/675\n * @see https://github.com/happyvertical/smrt/issues/688\n */\n\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\n/**\n * Resolved tenancy configuration for a single class, as stored in the registry.\n *\n * Every field has a concrete (non-optional) value — defaults are applied by\n * `registerTenantScopedClass()` when the class is registered via `@TenantScoped()`.\n *\n * @see TenantScopedOptions\n * @see registerTenantScopedClass\n */\nexport interface TenantScopedConfig {\n /**\n * Tenancy mode for this class\n * - 'required': Must have tenant context for all operations\n * - 'optional': Works with or without tenant context\n * @default 'required'\n */\n mode: 'required' | 'optional';\n\n /**\n * Field name containing tenant ID\n * @default 'tenantId'\n */\n field: string;\n\n /**\n * Auto-filter all queries by tenant\n * @default true\n */\n autoFilter: boolean;\n\n /**\n * Auto-populate tenant ID from context on create\n * @default true\n */\n autoPopulate: boolean;\n\n /**\n * Allow super admin bypass for this class\n * @default false\n */\n allowSuperAdminBypass: boolean;\n}\n\nconst DEFAULT_CONFIG: TenantScopedConfig = {\n mode: 'required',\n field: 'tenantId',\n autoFilter: true,\n autoPopulate: true,\n allowSuperAdminBypass: false,\n};\n\n// Registry storing tenant-scoped class configurations\nconst tenantScopedClasses = new Map<string, TenantScopedConfig>();\n\n/**\n * Register a class as tenant-scoped with the given configuration.\n *\n * Called automatically by the `@TenantScoped()` decorator. You can also call\n * this directly when you cannot use decorators (e.g., third-party classes or\n * plain objects in tests). Defaults from `DEFAULT_CONFIG` are merged over any\n * omitted options.\n *\n * Calling this again for the same `className` overwrites the previous entry.\n *\n * @param className - The class's `name` property (e.g., `'Document'`).\n * @param config - Partial tenancy configuration; omitted fields receive defaults.\n *\n * @example\n * ```typescript\n * // Manually register a class (e.g., for testing)\n * registerTenantScopedClass('Document', { mode: 'optional' });\n * ```\n *\n * @see TenantScoped\n * @see unregisterTenantScopedClass\n */\nexport function registerTenantScopedClass(\n className: string,\n config: Partial<TenantScopedConfig> = {},\n): void {\n tenantScopedClasses.set(className, {\n ...DEFAULT_CONFIG,\n ...config,\n });\n}\n\n/**\n * Remove a class from the tenant-scoped registry.\n *\n * Primarily intended for test teardown — use `clearTenantScopedRegistry()` to\n * reset the entire registry at once.\n *\n * @param className - The class name to remove (e.g., `'Document'`).\n *\n * @see clearTenantScopedRegistry\n * @see registerTenantScopedClass\n */\nexport function unregisterTenantScopedClass(className: string): void {\n tenantScopedClasses.delete(className);\n}\n\n/**\n * Strip a qualified `@scope/pkg:ClassName` name down to its bare class name.\n *\n * `@TenantScoped` registers classes by their simple name (`target.name`), but\n * `ObjectRegistry.getInheritanceChain()` emits **qualified** names where a\n * class has package context. The simple-name bridge this enables is confined to\n * the inheritance walk (`getInheritedTenantScopedConfig`) — never the direct\n * lookup — so a *direct* qualified lookup can't strip the namespace and\n * cross-match a same-simple-name class in another package.\n */\nfunction toSimpleClassName(className: string): string {\n const idx = className.lastIndexOf(':');\n return idx === -1 ? className : className.slice(idx + 1);\n}\n\n/**\n * Return a shallow copy of a config so callers can never mutate the stored\n * registration. The same backing object is shared by the base and every\n * inheriting descendant, so handing out the reference would let an accidental\n * caller mutation silently corrupt the base (and all children). (#1598 review)\n */\nfunction cloneConfig(config: TenantScopedConfig): TenantScopedConfig {\n return { ...config };\n}\n\n/**\n * Resolve a class's OWN tenancy configuration — no STI inheritance, EXACT name\n * match only.\n *\n * Checks the two registration mechanisms in order, with the local registry\n * taking precedence:\n * 1. The local registry populated by `@TenantScoped()` (keyed by simple name).\n * 2. The core `ObjectRegistry` populated by `@smrt({ tenantScoped: true })`.\n *\n * Lookups are by exact name only — no simple-name fallback — so a qualified\n * lookup (e.g. `@happyvertical/smrt-affiliates:Payout`, explicitly not scoped)\n * can never strip its namespace and match a same-simple-name scoped class in\n * another package (e.g. `@happyvertical/smrt-commerce:Payout`). The\n * namespace-stripping bridge lives only in the inheritance walk. (#1598 review)\n */\nfunction getDirectTenantScopedConfig(\n className: string,\n): TenantScopedConfig | undefined {\n // 1. Local registry (explicit @TenantScoped decorator).\n const localConfig = tenantScopedClasses.get(className);\n if (localConfig) {\n return cloneConfig(localConfig);\n }\n\n // 2. Core registry (@smrt({ tenantScoped: true }) pattern - Issue #688).\n // findClass() resolves qualified names package-safely, so this branch is\n // already disambiguated.\n const coreConfig = ObjectRegistry.getTenantScopedConfig(className);\n if (coreConfig) {\n // Convert core config to TenantScopedConfig format\n return {\n mode: coreConfig.mode,\n field: coreConfig.field,\n autoFilter: coreConfig.autoFilter,\n autoPopulate: coreConfig.autoPopulate,\n allowSuperAdminBypass: coreConfig.allowSuperAdminBypass,\n };\n }\n\n return undefined;\n}\n\n/**\n * Resolve tenancy configuration inherited from an STI/ancestor class.\n *\n * `@TenantScoped` (and `@smrt({ tenantScoped })`) register ONLY the exact class\n * decorated — recognition does NOT propagate to subclasses. Before #1596 this\n * meant an STI child with its own collection (the child is the collection's\n * `_itemClass`) was treated as non-tenant-scoped at runtime: the interceptor\n * skipped tenant filtering on its `list()`/`get()` (cross-tenant reads), skipped\n * tenant population in `beforeSave`, and skipped the raw-SQL policy. Manual\n * re-declaration on every child was the fragile pattern that already bit images\n * (#1407) and messages.\n *\n * We now walk the STI inheritance chain so any descendant of a tenant-scoped\n * base is recognized automatically and inherits the base's config. A subclass\n * of a tenant-scoped class is always itself tenant-scoped — there is no safe\n * reason for it to opt out — so the walk intentionally covers any inheritance\n * (the motivating leak is STI child collections, but this is correct for CTI\n * hierarchies too).\n *\n * Ancestors are walked from nearest-to-self toward the root, returning the\n * first tenant-scoped ancestor's config so a closer ancestor wins. The class's\n * OWN declaration is resolved by the direct lookup in `getTenantScopedConfig`\n * and always takes precedence over anything inherited here.\n */\nfunction getInheritedTenantScopedConfig(\n className: string,\n): TenantScopedConfig | undefined {\n // getInheritanceChain returns [root, ..., self] (qualified names where the\n // class has package context). It is cached by core and only reached here when\n // the direct lookup misses, so the per-call cost on non-tenant classes is a\n // cache hit plus this short loop. Returns [] for unregistered classes.\n const chain = ObjectRegistry.getInheritanceChain(className);\n // chain[length - 1] is the class itself (already covered by the direct\n // lookup); walk its ancestors from nearest to root.\n for (let i = chain.length - 2; i >= 0; i--) {\n const ancestor = chain[i];\n\n // Exact, package-safe match first — covers `@smrt({ tenantScoped })` bases\n // (resolved through the core registry by qualified name) and any class\n // whose @TenantScoped key matches the chain entry verbatim.\n const direct = getDirectTenantScopedConfig(ancestor);\n if (direct) {\n return direct;\n }\n\n // @TenantScoped registers by SIMPLE name (`target.name`), but the chain\n // emits QUALIFIED names. Bridge to the simple-keyed local registry here —\n // scoped to the inheritance walk only, so a direct qualified lookup never\n // strips the namespace (see getDirectTenantScopedConfig). The chain entry\n // is a verified ancestor of `className`, so matching its simple name is the\n // intended hop. (Residual: the @TenantScoped registry is simple-keyed, so\n // two DISTINCT same-simple-name classes that are BOTH @TenantScoped across\n // packages could cross-match here — a pre-existing decorator-keying limit,\n // not the direct-lookup hazard fixed above.)\n const simple = toSimpleClassName(ancestor);\n if (simple !== ancestor) {\n const bySimple = tenantScopedClasses.get(simple);\n if (bySimple) {\n return cloneConfig(bySimple);\n }\n }\n }\n return undefined;\n}\n\n/**\n * Retrieve the resolved tenancy configuration for a class.\n *\n * Resolution order:\n * 1. The class's OWN declaration — local `@TenantScoped()` registry first, then\n * the core `@smrt({ tenantScoped: true })` registry.\n * 2. STI inheritance — the nearest tenant-scoped ancestor's config (#1596).\n *\n * A class that declares its own tenancy never reaches step 2, so an explicit\n * child `@TenantScoped` always overrides the inherited base config.\n *\n * @param className - The class name to look up.\n * @returns The `TenantScopedConfig` if the class is tenant-scoped directly or\n * by inheritance, or `undefined` if it is not.\n *\n * @see isTenantScopedClass\n * @see getAllTenantScopedClasses\n */\nexport function getTenantScopedConfig(\n className: string,\n): TenantScopedConfig | undefined {\n // A class's own @TenantScoped / @smrt({ tenantScoped }) declaration wins.\n const direct = getDirectTenantScopedConfig(className);\n if (direct) {\n return direct;\n }\n // Otherwise inherit recognition from a tenant-scoped STI ancestor (#1596).\n return getInheritedTenantScopedConfig(className);\n}\n\n/**\n * Return `true` if the named class is tenant-scoped — directly (via\n * `@TenantScoped()` / `@smrt({ tenantScoped: true })`) or by inheriting from a\n * tenant-scoped STI ancestor (#1596).\n *\n * @param className - The class name to look up (e.g., `'Document'`).\n * @returns `true` if the class is tenant-scoped by any mechanism.\n *\n * @see getTenantScopedConfig\n * @see registerTenantScopedClass\n */\nexport function isTenantScopedClass(className: string): boolean {\n return getTenantScopedConfig(className) !== undefined;\n}\n\n/**\n * Return a snapshot of all classes registered via `@TenantScoped()`.\n *\n * Returns a new `Map` so mutations to the returned value do not affect the\n * internal registry. Note that classes registered only through the core\n * `ObjectRegistry` (`@smrt({ tenantScoped: true })`) are **not** included in\n * this map.\n *\n * @returns A copy of the local tenant-scoped class registry, keyed by class name.\n *\n * @see isTenantScopedClass\n * @see getTenantScopedConfig\n */\nexport function getAllTenantScopedClasses(): Map<string, TenantScopedConfig> {\n return new Map(tenantScopedClasses);\n}\n\n/**\n * Remove all entries from the local tenant-scoped class registry.\n *\n * Intended for test teardown via `resetTenancy()`. Does not affect\n * registrations held by the core `ObjectRegistry`.\n *\n * @see resetTenancy\n * @see unregisterTenantScopedClass\n */\nexport function clearTenantScopedRegistry(): void {\n tenantScopedClasses.clear();\n}\n","/**\n * Shared tenancy-enabled flag.\n *\n * Holds the single boolean toggled by `enableTenancy()` / `disableTenancy()`.\n * It lives in its own leaf module (importing nothing from the package) so that\n * both `interceptor.ts` and `entry-point.ts` can read it without forming a\n * circular import: `interceptor.ts` imports `runTenantScopedEntryPoint` from\n * `entry-point.ts`, and `entry-point.ts` needs the enabled flag — routing the\n * flag through here keeps that dependency one-directional.\n */\n\nlet enabled = false;\n\n/**\n * Set the global tenancy-enabled flag. Internal — called by `enableTenancy()` /\n * `disableTenancy()` in `interceptor.ts`.\n *\n * @param value - `true` to mark tenancy enabled, `false` to clear it.\n */\nexport function setTenancyEnabled(value: boolean): void {\n enabled = value;\n}\n\n/**\n * Return `true` if tenant enforcement is currently active.\n *\n * @returns Whether `enableTenancy()` has been called without a later\n * `disableTenancy()`.\n */\nexport function isTenancyEnabled(): boolean {\n return enabled;\n}\n","/**\n * Fail-closed tenant-context establishment for non-web entry points (#1554).\n *\n * The SvelteKit/Express adapters establish tenant context from the authenticated\n * request principal, so the web surface of a `@TenantScoped({ mode: 'optional' })`\n * model never reads across tenants without an active context. A generated\n * in-process entry point has no request principal, so an invocation with no\n * active context would fall through the interceptor's optional-mode\n * pass-through and return rows across **all** tenants.\n *\n * `runTenantScopedEntryPoint()` closes that gap. `@happyvertical/smrt-core`'s\n * `MCPGenerator` is the only in-repo generated surface that wraps its\n * per-tool execution in this gate today (via `setTenantEntryPointRunner`\n * below). Core's `CLIGenerator`, which used to wrap its per-command execution\n * in the same gate, was retired as unused public API (#2664); the live local\n * CLI transport (`packages/cli/src/cli-generator.ts`, the shipped `smrt\n * <object>:<action>` binary) has never called this gate and is not\n * tenant-isolation fail-closed today.\n *\n * @see createCliContext for a hand-wired CLI runner (resolveTenantId,\n * super-admin) a consuming application can use directly — independent of\n * the generated-surface gate above and unaffected by #2664.\n */\n\nimport {\n hasTenantContext,\n isSystemContext,\n TenantContextError,\n withSystemContext,\n withTenant,\n} from './context.js';\nimport { isTenancyEnabled } from './enabled-state.js';\nimport { isTenantScopedClass } from './registry.js';\n\n/**\n * Inputs for {@link runTenantScopedEntryPoint}.\n *\n * Provide **either** `className` (the gate resolves tenant-scoping from the\n * authoritative tenancy registry — the same source the interceptor uses, so it\n * covers both `@TenantScoped` and `@smrt({ tenantScoped })` registrations) or an\n * explicit `tenantScoped` boolean (when the caller already resolved it, e.g. a\n * build-time generated surface). An explicit boolean wins when both are given.\n */\nexport interface TenantEntryPointOptions {\n /**\n * Class name of the target model. When provided, tenant-scoping is resolved\n * via `isTenantScopedClass(className)`.\n */\n className?: string;\n\n /**\n * Explicit tenant-scoping decision. Overrides `className` resolution when set.\n * Non-scoped models always pass through unchanged — the gate is a no-op.\n */\n tenantScoped?: boolean;\n\n /**\n * Explicit operator-provided tenant selector (CLI `--tenant <id>`, MCP\n * `context.tenantId`). When present (and no context is already active) the\n * function runs inside this tenant's context.\n */\n tenantId?: string | null;\n\n /**\n * Explicit operator opt-in to cross-tenant / system access (CLI\n * `--all-tenants`, an MCP host that trusts the caller as an operator). When\n * set the function runs in system context, bypassing tenant filtering.\n *\n * @default false\n */\n allowCrossTenant?: boolean;\n\n /**\n * Human-facing surface name used in the fail-closed error message, e.g.\n * `'CLI'` or `'MCP'`.\n *\n * @default 'entry point'\n */\n surface?: string;\n}\n\n/**\n * Run `fn` inside an appropriate tenant context for a generated in-process\n * entry point (MCP today, see the module docblock above), failing closed for\n * tenant-scoped models when no authorized context can be established.\n *\n * Resolution order (tenant-scoped models only):\n * 1. A tenant context is already active, or an explicit `withSystemContext()`\n * bypass is in effect (e.g. `runAsSystem()`, migrations) → run as-is.\n * 2. `allowCrossTenant` was explicitly set → run in system context. Checked\n * before `tenantId` so an explicit cross-tenant opt-in wins over a default\n * principal/host tenant rather than being silently scoped.\n * 3. An explicit `tenantId` was provided → run inside that tenant.\n * 4. Tenancy is enabled but none of the above → **throw** `TenantContextError`\n * (the fail-closed branch — never silently read across tenants).\n * 5. Tenancy is disabled (single-/no-tenant deployment) → pass through.\n *\n * Non-tenant-scoped models always pass straight through.\n *\n * @param options - {@link TenantEntryPointOptions}.\n * @param fn - The command/tool body to execute.\n * @returns The resolved value of `fn`.\n * @throws {TenantContextError} When a tenant-scoped model is reached with\n * tenancy enabled and no tenant/cross-tenant selector.\n */\nexport async function runTenantScopedEntryPoint<T>(\n options: TenantEntryPointOptions,\n fn: () => Promise<T>,\n): Promise<T> {\n const {\n className,\n tenantScoped,\n tenantId,\n allowCrossTenant = false,\n surface = 'entry point',\n } = options;\n\n // Resolve tenant-scoping: an explicit boolean wins; otherwise consult the\n // authoritative tenancy registry by class name (matches the interceptor).\n const scoped =\n typeof tenantScoped === 'boolean'\n ? tenantScoped\n : className\n ? isTenantScopedClass(className)\n : false;\n\n // Non-scoped models run as-is. So do calls already inside a tenant context\n // (an upstream handle) or an explicit system-context bypass — the interceptor\n // honors `withSystemContext()` (migrations, `runAsSystem()`), so the gate must\n // not fail-close over it (hasTenantContext() is false for the system marker).\n if (!scoped) return fn();\n if (hasTenantContext() || isSystemContext()) return fn();\n\n // Explicit operator opt-in to cross-tenant access. Checked before the tenant\n // selector so a deliberate `--all-tenants` / `allowCrossTenant` overrides a\n // default host/principal tenant instead of being silently scoped to it.\n if (allowCrossTenant) {\n return withSystemContext(fn);\n }\n\n // Explicit tenant selector.\n if (typeof tenantId === 'string' && tenantId) {\n return withTenant({ tenantId }, fn);\n }\n\n // Fail closed: tenancy is on but the caller gave us nothing to scope by.\n if (isTenancyEnabled()) {\n throw new TenantContextError(\n `Tenant context required for tenant-scoped access via ${surface}. ` +\n 'Pass an explicit tenant (e.g. --tenant <id> / a tenantId) or opt into ' +\n 'cross-tenant access (e.g. --all-tenants) to read across all tenants.',\n );\n }\n\n // Tenancy disabled → single-tenant deployment, pass through.\n return fn();\n}\n","/**\n * Tenant Interceptor - Core enforcement mechanism\n *\n * Registers with GlobalInterceptors in smrt-core to automatically:\n * - Filter queries by tenant ID\n * - Validate tenant context on save/delete\n * - Block or audit raw SQL on tenant-scoped classes\n *\n * @see https://github.com/happyvertical/smrt/issues/675\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport type { SmrtObject } from '@happyvertical/smrt-core';\nimport {\n type CollectionInterceptor,\n type DispatchBus,\n GlobalInterceptors,\n type InterceptorContext,\n type ListOptions,\n type QueryInterceptResult,\n type QueryOptions,\n resolveGetStringFilter,\n setDispatchTenantResolver,\n setTenantEntryPointRunner,\n setTenantScopedClassResolver,\n} from '@happyvertical/smrt-core';\nimport {\n getCurrentTenant,\n getTenantId,\n isSuperAdminBypass,\n isSystemContext,\n TenantContextError,\n TenantIsolationError,\n} from './context.js';\nimport { isTenancyEnabled, setTenancyEnabled } from './enabled-state.js';\nimport { runTenantScopedEntryPoint } from './entry-point.js';\nimport { getTenantScopedConfig, isTenantScopedClass } from './registry.js';\n\nconst logger = createLogger({ level: 'info' });\n\n/**\n * Policy controlling what happens when raw SQL is executed against a\n * tenant-scoped class without an explicit bypass.\n *\n * - `'throw'` — Raises a `TenantIsolationError` (most secure; default).\n * - `'warn'` — Logs a `console.warn` but allows the query to proceed (useful\n * during migration periods).\n * - `'allow'` — Silently allows the query; not recommended for production.\n *\n * @see TenantInterceptorOptions.rawQueryPolicy\n * @see enableTenancy\n */\nexport type RawQueryPolicy = 'throw' | 'warn' | 'allow';\n\n/**\n * Configuration options accepted by `createTenantInterceptor()` and\n * `enableTenancy()`.\n *\n * All options are optional; reasonable defaults are applied. The callback\n * hooks (`onRawQuery`, `onMissingContext`, `onIsolationViolation`) are useful\n * for logging and alerting without altering the enforcement behaviour.\n *\n * @see createTenantInterceptor\n * @see enableTenancy\n */\nexport interface TenantInterceptorOptions {\n /**\n * Policy for raw SQL queries on tenant-scoped classes\n * - 'throw': Throw error (most secure, default)\n * - 'warn': Log warning but allow (for migration)\n * - 'allow': Silently allow (not recommended for production)\n * @default 'throw'\n */\n rawQueryPolicy?: RawQueryPolicy;\n\n /**\n * Called when a raw query is attempted on a tenant-scoped class\n * Useful for logging/auditing\n */\n onRawQuery?: (\n className: string,\n sql: string,\n context: InterceptorContext,\n ) => void;\n\n /**\n * Called when tenant context is missing for a tenant-scoped operation\n */\n onMissingContext?: (\n className: string,\n operation: string,\n context: InterceptorContext,\n ) => void;\n\n /**\n * Called when an isolation violation is detected\n */\n onIsolationViolation?: (\n className: string,\n expectedTenantId: string,\n actualTenantId: string,\n context: InterceptorContext,\n ) => void;\n\n /**\n * DispatchBus instance for emitting provisioning events on lifecycle changes.\n * When provided along with directoryClasses, afterSave/afterDelete hooks\n * emit dispatches like `directory.membership.created`.\n */\n dispatchBus?: DispatchBus;\n\n /**\n * Class names to emit directory dispatches for on save/delete lifecycle events.\n * Only classes listed here will trigger dispatch emissions.\n * @example ['Tenant', 'Membership', 'User']\n */\n directoryClasses?: string[];\n}\n\nconst DEFAULT_OPTIONS: TenantInterceptorOptions = {\n rawQueryPolicy: 'throw',\n};\n\n/**\n * Extract a plain-object snapshot of an instance for dispatch payloads.\n *\n * Prefers `toJSON()` when available (all real SmrtObject instances) because\n * it returns only data fields and excludes internal handles like `_db`, `_ai`,\n * and `_fs` which may contain circular references (e.g. connection pools with\n * Timeout objects).\n *\n * @see https://github.com/happyvertical/smrt/issues/946\n */\nfunction serializeInstance(\n instance: SmrtObject,\n className: string,\n): Record<string, unknown> {\n // Documented exception to the \"never call toJSON() directly\" convention\n // (docs/content/standards.md §7): the interceptor must serialize whatever\n // instance is handed to it, including workspace stubs and plain-object\n // doubles used in unit tests whose classes may not extend SmrtObject and\n // therefore have no `transformJSON()` hook. Using `toJSON()` here is a\n // duck-typed fallback — when present, it strips framework-internal handles\n // for us; when absent, we fall through to manual key iteration below.\n const maybeToJSON = (instance as { toJSON?: unknown }).toJSON;\n if (typeof maybeToJSON === 'function') {\n return {\n className,\n ...(maybeToJSON.call(instance) as Record<string, unknown>),\n };\n }\n\n // Fallback for plain-object stubs (e.g. in unit tests):\n // skip functions and framework-internal properties\n const result: Record<string, unknown> = { className };\n const record = instance as unknown as Record<string, unknown>;\n for (const key of Object.keys(instance)) {\n const value = record[key];\n if (typeof value !== 'function') {\n result[key] = value;\n }\n }\n return result;\n}\n\n/**\n * Create a `CollectionInterceptor` that enforces tenant isolation on all\n * `SmrtCollection` operations.\n *\n * The returned interceptor hooks into the smrt-core `GlobalInterceptors`\n * pipeline at priority 100 (runs before all other interceptors) and\n * handles the following lifecycle hooks:\n *\n * | Hook | Behaviour |\n * |---------------|-----------|\n * | `beforeList` | Injects tenant filter into `WHERE`; validates explicit filters. |\n * | `beforeGet` | Resolves string lookups (id vs slug) and adds the tenant predicate. |\n * | `beforeSave` | Auto-populates `tenantId`; validates existing values. |\n * | `beforeDelete`| Validates the instance's `tenantId` matches context. |\n * | `beforeQuery` | Enforces `rawQueryPolicy` on raw SQL calls. |\n * | `afterSave` | Emits `directory.<class>.created/updated` via `dispatchBus`. |\n * | `afterDelete` | Emits `directory.<class>.deleted` via `dispatchBus`. |\n *\n * Use `enableTenancy()` to register the interceptor globally. Call this\n * directly only when you need multiple interceptor instances (e.g., for\n * isolated tests or feature flags).\n *\n * @param options - Configuration for the interceptor.\n * @returns A `CollectionInterceptor` ready to be registered with\n * `GlobalInterceptors.register()`.\n *\n * @example\n * ```typescript\n * import { createTenantInterceptor } from '@happyvertical/smrt-tenancy';\n * import { GlobalInterceptors } from '@happyvertical/smrt-core';\n *\n * const interceptor = createTenantInterceptor({ rawQueryPolicy: 'warn' });\n * GlobalInterceptors.register(interceptor);\n * ```\n *\n * @see enableTenancy\n * @see TenantInterceptorOptions\n */\nexport function createTenantInterceptor(\n options: TenantInterceptorOptions = {},\n): CollectionInterceptor {\n const opts = { ...DEFAULT_OPTIONS, ...options };\n\n return {\n name: 'smrt-tenancy',\n priority: 100, // High priority - should run first\n\n /**\n * Before list: Add tenant filter to queries\n */\n beforeList(\n className: string,\n listOptions: ListOptions,\n context: InterceptorContext,\n ): ListOptions | undefined {\n // Check if this class is tenant-scoped\n if (!isTenantScopedClass(className)) {\n return; // Not tenant-scoped, pass through\n }\n\n // Check for super admin bypass\n if (isSuperAdminBypass()) {\n return; // Bypass enabled, pass through\n }\n\n // Check for system context (explicit bypass via withSystemContext)\n if (isSystemContext()) {\n return; // System context bypasses tenant checks\n }\n\n const config = getTenantScopedConfig(className);\n const tenantContext = getCurrentTenant();\n\n // If no tenant context and mode is 'required', throw\n if (!tenantContext) {\n if (config?.mode === 'required') {\n opts.onMissingContext?.(className, 'list', context);\n throw new TenantContextError(\n `Tenant context required for listing ${className}. ` +\n `Use withTenant() or configure TenantContext middleware.`,\n );\n }\n return; // Mode is 'optional', allow without filtering\n }\n\n // Add tenant filter to where clause\n const tenantField = config?.field || 'tenantId';\n const where = listOptions.where || {};\n\n // Preserve DNF predicates (outer OR, inner AND) by applying the tenant\n // predicate to every branch. Flattening this shape into an object would\n // make one branch escape tenant scope, so validate direct tenant filters\n // branch-by-branch before adding the current tenant where absent.\n if (Array.isArray(where)) {\n if (\n where.length === 0 ||\n where.some((andGroup) => andGroup.length === 0)\n ) {\n throw new Error(\n 'Invalid DNF where clause: every OR branch must contain at least one condition',\n );\n }\n const scopedWhere = where.map((andGroup) => {\n const directValues = andGroup.flatMap((condition) => {\n if (!Object.hasOwn(condition, tenantField)) return [];\n const value = condition[tenantField];\n return Array.isArray(value) ? value : [value];\n });\n const offendingIndex = directValues.findIndex(\n (value) => value !== tenantContext.tenantId,\n );\n if (offendingIndex !== -1) {\n const offending = directValues[offendingIndex];\n opts.onIsolationViolation?.(\n className,\n tenantContext.tenantId,\n String(offending),\n context,\n );\n throw new TenantIsolationError(\n `Tenant isolation violation in ${className} query: ` +\n `context tenant is '${tenantContext.tenantId}' but query filters by '${String(offending)}'`,\n {\n tenantId: tenantContext.tenantId,\n attemptedTenantId: String(offending),\n },\n );\n }\n return directValues.length > 0\n ? andGroup\n : [...andGroup, { [tenantField]: tenantContext.tenantId }];\n });\n return { ...listOptions, where: scopedWhere };\n }\n\n // Check if tenant filter is already present\n if (tenantField in where) {\n // Validate it matches context. The filter may be a scalar\n // (`tenantId: 'x'`) or an IN-style array (`tenantId: ['x']`) —\n // smrt-core auto-converts array values to SQL IN clauses, so an\n // array containing only the context tenant is a valid filter.\n // See https://github.com/happyvertical/smrt/issues/1495\n const existingFilter = where[tenantField];\n const filterValues = Array.isArray(existingFilter)\n ? existingFilter\n : [existingFilter];\n // findIndex (not find) so a literal null/undefined filter value is\n // still flagged as a violation rather than mistaken for \"not found\"\n const offendingIndex = filterValues.findIndex(\n (value) => value !== tenantContext.tenantId,\n );\n if (offendingIndex !== -1) {\n const offending = filterValues[offendingIndex];\n opts.onIsolationViolation?.(\n className,\n tenantContext.tenantId,\n String(offending),\n context,\n );\n throw new TenantIsolationError(\n `Tenant isolation violation in ${className} query: ` +\n `context tenant is '${tenantContext.tenantId}' but query filters by '${String(offending)}'`,\n {\n tenantId: tenantContext.tenantId,\n attemptedTenantId: String(offending),\n },\n );\n }\n return; // Filter already correct\n }\n\n // Inject tenant filter\n return {\n ...listOptions,\n where: {\n ...where,\n [tenantField]: tenantContext.tenantId,\n },\n };\n },\n\n /**\n * Before get: Add tenant filter to single record fetches\n */\n beforeGet(\n className: string,\n filter: string | Record<string, unknown>,\n context: InterceptorContext,\n ): string | Record<string, unknown> | undefined {\n if (!isTenantScopedClass(className)) {\n return;\n }\n\n if (isSuperAdminBypass()) {\n return;\n }\n\n // Check for system context (explicit bypass via withSystemContext)\n if (isSystemContext()) {\n return; // System context bypasses tenant checks\n }\n\n const config = getTenantScopedConfig(className);\n const tenantContext = getCurrentTenant();\n\n if (!tenantContext) {\n if (config?.mode === 'required') {\n opts.onMissingContext?.(className, 'get', context);\n throw new TenantContextError(\n `Tenant context required for getting ${className}. ` +\n `Use withTenant() or configure TenantContext middleware.`,\n );\n }\n return;\n }\n\n const tenantField = config?.field || 'tenantId';\n\n // If filter is a string, resolve it exactly the way core's `get()` would\n // (UUID -> id lookup, anything else -> slug/context natural key) and add\n // the tenant predicate to whichever shape it resolves to. Rewriting every\n // string to `{ id: filter }` broke get-by-slug under a tenant context:\n // null on SQLite, a uuid cast error on PostgreSQL (#2365).\n if (typeof filter === 'string') {\n return {\n ...resolveGetStringFilter(filter),\n [tenantField]: tenantContext.tenantId,\n };\n }\n\n // Add tenant filter to object\n if (!(tenantField in filter)) {\n return {\n ...filter,\n [tenantField]: tenantContext.tenantId,\n };\n }\n\n // Validate existing filter. Like beforeList, accept scalar or\n // IN-style array filters (smrt-core auto-converts arrays to SQL IN).\n // See https://github.com/happyvertical/smrt/issues/1495\n const existingFilter = filter[tenantField];\n const filterValues = Array.isArray(existingFilter)\n ? existingFilter\n : [existingFilter];\n // findIndex (not find) so a literal null/undefined filter value is\n // still flagged as a violation rather than mistaken for \"not found\"\n const offendingIndex = filterValues.findIndex(\n (value) => value !== tenantContext.tenantId,\n );\n if (offendingIndex !== -1) {\n const offending = filterValues[offendingIndex];\n opts.onIsolationViolation?.(\n className,\n tenantContext.tenantId,\n String(offending),\n context,\n );\n throw new TenantIsolationError(\n `Tenant isolation violation in ${className} get: ` +\n `context tenant is '${tenantContext.tenantId}' but query filters by '${String(offending)}'`,\n {\n tenantId: tenantContext.tenantId,\n attemptedTenantId: String(offending),\n },\n );\n }\n\n return;\n },\n\n /**\n * Before query: Handle raw SQL on tenant-scoped classes\n */\n beforeQuery(\n className: string,\n queryOptions: QueryOptions,\n context: InterceptorContext,\n ): QueryInterceptResult | undefined {\n if (!isTenantScopedClass(className)) {\n return;\n }\n\n // Check for explicit bypass flag\n if (queryOptions.allowRawOnTenantScoped) {\n opts.onRawQuery?.(className, queryOptions.sql, context);\n return; // Explicitly allowed\n }\n\n if (isSuperAdminBypass()) {\n opts.onRawQuery?.(className, queryOptions.sql, context);\n return;\n }\n\n // Check for system context (explicit bypass via withSystemContext)\n if (isSystemContext()) {\n opts.onRawQuery?.(className, queryOptions.sql, context);\n return;\n }\n\n // Handle based on policy\n const message =\n `Raw SQL query attempted on tenant-scoped class ${className}. ` +\n `Use list()/get() for automatic tenant filtering, or call ` +\n `query() with { allowRawOnTenantScoped: true } if you're handling ` +\n `tenant filtering manually.`;\n\n opts.onRawQuery?.(className, queryOptions.sql, context);\n\n switch (opts.rawQueryPolicy) {\n case 'throw':\n throw new TenantIsolationError(message);\n\n case 'warn':\n logger.warn(`[smrt-tenancy] WARNING: ${message}`);\n return;\n default:\n return;\n }\n },\n\n /**\n * Before save: Validate tenant ID is set and matches context\n */\n beforeSave(instance: SmrtObject, context: InterceptorContext): void {\n // Use context.className which is always correct\n // (instance.constructor.name may not match for proxies or plain objects in tests)\n const className = context.className;\n\n // Stash isNew flag for afterSave dispatch detection\n if (opts.directoryClasses?.includes(className)) {\n const id = (instance as unknown as Record<string, unknown>).id;\n context.metadata = {\n ...context.metadata,\n _directoryIsNew: id === undefined || id === null,\n };\n }\n\n if (!isTenantScopedClass(className)) {\n return;\n }\n\n if (isSuperAdminBypass()) {\n return;\n }\n\n // Check for system context (explicit bypass via withSystemContext)\n if (isSystemContext()) {\n return; // System context bypasses tenant checks\n }\n\n const config = getTenantScopedConfig(className);\n const tenantField = config?.field || 'tenantId';\n const instanceRecord = instance as unknown as Record<string, unknown>;\n const instanceTenantId = instanceRecord[tenantField];\n\n const tenantContext = getCurrentTenant();\n\n // Check if tenant context is required\n if (!tenantContext) {\n if (config?.mode === 'required') {\n opts.onMissingContext?.(className, 'save', context);\n throw new TenantContextError(\n `Tenant context required for saving ${className}. ` +\n `Use withTenant() or configure TenantContext middleware.`,\n );\n }\n return; // Mode is 'optional'\n }\n\n // Auto-populate tenant ID if not set\n if (!instanceTenantId && config?.autoPopulate !== false) {\n instanceRecord[tenantField] = tenantContext.tenantId;\n return;\n }\n\n // Validate tenant ID matches context\n if (instanceTenantId && instanceTenantId !== tenantContext.tenantId) {\n const attemptedTenantId = String(instanceTenantId);\n opts.onIsolationViolation?.(\n className,\n tenantContext.tenantId,\n attemptedTenantId,\n context,\n );\n throw new TenantIsolationError(\n `Tenant isolation violation: cannot save ${className} with ` +\n `tenantId '${attemptedTenantId}' in context of tenant '${tenantContext.tenantId}'`,\n {\n tenantId: tenantContext.tenantId,\n attemptedTenantId,\n },\n );\n }\n },\n\n /**\n * Before delete: Validate instance belongs to current tenant\n */\n beforeDelete(instance: SmrtObject, context: InterceptorContext): void {\n // Use context.className which is always correct\n const className = context.className;\n\n if (!isTenantScopedClass(className)) {\n return;\n }\n\n if (isSuperAdminBypass()) {\n return;\n }\n\n // Check for system context (explicit bypass via withSystemContext)\n if (isSystemContext()) {\n return; // System context bypasses tenant checks\n }\n\n const config = getTenantScopedConfig(className);\n const tenantField = config?.field || 'tenantId';\n const instanceTenantId = (instance as unknown as Record<string, unknown>)[\n tenantField\n ];\n\n const tenantContext = getCurrentTenant();\n\n if (!tenantContext) {\n if (config?.mode === 'required') {\n opts.onMissingContext?.(className, 'delete', context);\n throw new TenantContextError(\n `Tenant context required for deleting ${className}. ` +\n `Use withTenant() or configure TenantContext middleware.`,\n );\n }\n return;\n }\n\n // Validate tenant ID matches\n if (instanceTenantId && instanceTenantId !== tenantContext.tenantId) {\n const attemptedTenantId = String(instanceTenantId);\n opts.onIsolationViolation?.(\n className,\n tenantContext.tenantId,\n attemptedTenantId,\n context,\n );\n throw new TenantIsolationError(\n `Tenant isolation violation: cannot delete ${className} with ` +\n `tenantId '${attemptedTenantId}' in context of tenant '${tenantContext.tenantId}'`,\n {\n tenantId: tenantContext.tenantId,\n attemptedTenantId,\n },\n );\n }\n },\n\n /**\n * After save: Emit directory dispatch for configured classes\n */\n async afterSave(\n instance: SmrtObject,\n context: InterceptorContext,\n ): Promise<void> {\n if (\n !opts.dispatchBus ||\n !opts.directoryClasses?.includes(context.className)\n )\n return;\n\n const instanceId = (instance as unknown as Record<string, unknown>).id;\n const sourceId = typeof instanceId === 'string' ? instanceId : undefined;\n const rawIsNew = context.metadata?._directoryIsNew;\n const isNew =\n typeof rawIsNew === 'boolean' ? rawIsNew : instanceId == null;\n const event = isNew\n ? `directory.${context.className.toLowerCase()}.created`\n : `directory.${context.className.toLowerCase()}.updated`;\n\n await opts.dispatchBus.emit(\n event,\n serializeInstance(instance, context.className),\n {\n source: 'smrt-tenancy',\n sourceId,\n },\n );\n },\n\n /**\n * After delete: Emit directory dispatch for configured classes\n */\n async afterDelete(\n instance: SmrtObject,\n context: InterceptorContext,\n ): Promise<void> {\n if (\n !opts.dispatchBus ||\n !opts.directoryClasses?.includes(context.className)\n )\n return;\n\n const instanceId = (instance as unknown as Record<string, unknown>).id;\n await opts.dispatchBus.emit(\n `directory.${context.className.toLowerCase()}.deleted`,\n serializeInstance(instance, context.className),\n {\n source: 'smrt-tenancy',\n sourceId: typeof instanceId === 'string' ? instanceId : undefined,\n },\n );\n },\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Registration Functions\n// ─────────────────────────────────────────────────────────────────────────────\n\n// The enabled flag lives in `enabled-state.ts` (a leaf module) so `entry-point.ts`\n// can read it without importing this module — breaking the otherwise-circular\n// interceptor ↔ entry-point dependency.\nlet registeredInterceptor: CollectionInterceptor | null = null;\n\n/**\n * Enable tenant enforcement globally\n *\n * Call this once at application startup to enable automatic tenant isolation.\n *\n * @param options - Configuration options\n *\n * @example\n * ```typescript\n * // In your app initialization\n * import { enableTenancy } from '@happyvertical/smrt-tenancy';\n *\n * enableTenancy({\n * rawQueryPolicy: 'throw',\n * onMissingContext: (className, operation) => {\n * console.error(`Missing tenant context for ${operation} on ${className}`);\n * }\n * });\n * ```\n */\nexport function enableTenancy(options: TenantInterceptorOptions = {}): void {\n if (isTenancyEnabled()) {\n logger.warn(\n '[smrt-tenancy] Tenancy is already enabled. Call disableTenancy() first to reconfigure.',\n );\n return;\n }\n\n registeredInterceptor = createTenantInterceptor(options);\n GlobalInterceptors.register(registeredInterceptor);\n\n // Wire the DispatchBus tenant-scope resolver (S5 #1398). Core cannot depend\n // on tenancy, so it reads the active tenant through this injected hook; the\n // bus stamps/filters dispatches by the active tenant only while tenancy is\n // enabled. Mirrors the GlobalInterceptors inversion above.\n setDispatchTenantResolver(() => getTenantId());\n\n // Wire the fail-closed tenant gate for generated in-process entry points\n // (#1554). Core's MCPGenerator invokes this runner around tenant-scoped MCP\n // execution; without it (tenancy disabled) that surface passes through\n // unchanged. Core's CLIGenerator used to invoke it too but was retired as\n // unused public API (#2664); the shipped local CLI transport\n // (packages/cli/src/cli-generator.ts) has never called it.\n setTenantEntryPointRunner(runTenantScopedEntryPoint);\n\n // Wire the tenant-scoped-class resolver so core-side fail-closed read guards\n // (generated REST read scope, #1782) recognize `@TenantScoped()`-decorated\n // classes, which record their config only in the tenancy registry.\n setTenantScopedClassResolver((className) => isTenantScopedClass(className));\n\n setTenancyEnabled(true);\n}\n\n/**\n * Disable global tenant enforcement.\n *\n * Unregisters the interceptor previously installed by `enableTenancy()` and\n * resets the internal enabled flag so `enableTenancy()` can be called again.\n * Idempotent — safe to call even when tenancy was never enabled.\n *\n * Common use-cases:\n * - Test teardown (via `resetTenancy()`).\n * - Temporarily disabling tenancy before reconfiguring with new options.\n *\n * @example\n * ```typescript\n * afterAll(() => {\n * disableTenancy();\n * });\n * ```\n *\n * @see enableTenancy\n * @see isTenancyEnabled\n * @see resetTenancy\n */\nexport function disableTenancy(): void {\n if (!isTenancyEnabled() || !registeredInterceptor) {\n return;\n }\n\n GlobalInterceptors.unregister(registeredInterceptor);\n // Clear the DispatchBus tenant resolver so the bus reverts to its no-op\n // (pre-tenancy) behavior when tenancy is disabled.\n setDispatchTenantResolver(undefined);\n // Clear the in-process tenant gate so that surface (MCP) passes through\n // (#1554).\n setTenantEntryPointRunner(undefined);\n // Clear the tenant-scoped-class resolver (#1782).\n setTenantScopedClassResolver(undefined);\n registeredInterceptor = null;\n setTenancyEnabled(false);\n}\n\n/**\n * Return `true` if tenant enforcement is currently active.\n *\n * Reflects whether `enableTenancy()` has been called and the interceptor has not\n * yet been removed by `disableTenancy()`. Re-exported from `enabled-state.ts`\n * (the shared leaf module) so the public API surface is unchanged.\n *\n * @see enableTenancy\n * @see disableTenancy\n */\nexport { isTenancyEnabled };\n","/**\n * Testing Utilities for smrt-tenancy\n *\n * Helpers for testing tenant-scoped applications.\n *\n * @example\n * ```typescript\n * import { createTestTenantContext, resetTenancy } from '@happyvertical/smrt-tenancy/testing';\n *\n * beforeEach(() => {\n * resetTenancy(); // Clear all state\n * });\n *\n * it('should filter by tenant', async () => {\n * await createTestTenantContext({ tenantId: 'tenant-1' }, async () => {\n * const docs = await collection.list({});\n * // Only tenant-1 documents\n * });\n * });\n * ```\n */\n\nimport {\n type MinimalTenantContext,\n type TenantContextData,\n withTenant,\n} from './context.js';\nimport { disableTenancy, enableTenancy } from './interceptor.js';\nimport { clearTenantScopedRegistry } from './registry.js';\n\n/**\n * Reset all tenancy state (for use in beforeEach/afterEach)\n *\n * This clears:\n * - Registered interceptors\n * - Tenant-scoped class registry\n *\n * @example\n * ```typescript\n * afterEach(() => {\n * resetTenancy();\n * });\n * ```\n */\nexport function resetTenancy(): void {\n disableTenancy();\n clearTenantScopedRegistry();\n}\n\n/**\n * Create a test tenant context and run code within it\n *\n * Convenience wrapper around withTenant() with sensible defaults for testing.\n *\n * @param context - Tenant context (can be minimal, just tenantId)\n * @param fn - Async function to run in the context\n *\n * @example\n * ```typescript\n * await createTestTenantContext({ tenantId: 'test-tenant' }, async () => {\n * const product = await collection.create({ name: 'Test' });\n * expect(product.tenantId).toBe('test-tenant');\n * });\n * ```\n */\nexport async function createTestTenantContext<T>(\n context: MinimalTenantContext | TenantContextData,\n fn: () => Promise<T>,\n): Promise<T> {\n return withTenant(context, fn);\n}\n\n/**\n * Create multiple tenant contexts for isolation testing\n *\n * @param tenantIds - Array of tenant IDs to create contexts for\n * @param fn - Function that receives an object mapping tenant IDs to context runners\n *\n * @example\n * ```typescript\n * await testTenantIsolation(['tenant-a', 'tenant-b'], async (tenants) => {\n * // Create in tenant A\n * const docA = await tenants['tenant-a'](async () => {\n * return collection.create({ title: 'A doc' });\n * });\n *\n * // Verify not visible in tenant B\n * await tenants['tenant-b'](async () => {\n * const found = await collection.get(docA.id);\n * expect(found).toBeNull();\n * });\n * });\n * ```\n */\nexport async function testTenantIsolation<T>(\n tenantIds: string[],\n fn: (\n tenants: Record<string, <R>(runner: () => Promise<R>) => Promise<R>>,\n ) => Promise<T>,\n): Promise<T> {\n const tenants: Record<string, <R>(runner: () => Promise<R>) => Promise<R>> =\n {};\n\n for (const tenantId of tenantIds) {\n tenants[tenantId] = async <R>(runner: () => Promise<R>) => {\n return withTenant({ tenantId }, runner);\n };\n }\n\n return fn(tenants);\n}\n\n/**\n * Options for `setupTestTenancy()`.\n *\n * @see setupTestTenancy\n */\nexport interface SetupTestTenancyOptions {\n /**\n * Enable tenancy interceptors\n * @default true\n */\n enableInterceptors?: boolean;\n\n /**\n * Raw query policy for tests\n * @default 'throw'\n */\n rawQueryPolicy?: 'throw' | 'warn' | 'allow';\n}\n\n/**\n * Set up tenancy for a test suite\n *\n * Call in beforeAll or at the start of tests to configure tenancy.\n *\n * @param options - Setup options\n *\n * @example\n * ```typescript\n * beforeAll(() => {\n * setupTestTenancy({ enableInterceptors: true });\n * });\n *\n * afterAll(() => {\n * resetTenancy();\n * });\n * ```\n */\nexport function setupTestTenancy(options: SetupTestTenancyOptions = {}): void {\n const { enableInterceptors = true, rawQueryPolicy = 'throw' } = options;\n\n // Clear any existing state\n resetTenancy();\n\n // Enable interceptors if requested\n if (enableInterceptors) {\n enableTenancy({ rawQueryPolicy });\n }\n}\n\n/**\n * Assert that executing `fn` throws a `TenantContextError`.\n *\n * Fails with a descriptive message if `fn` completes without throwing, or if\n * it throws a different error type. Optionally verifies that the error message\n * contains a specific substring.\n *\n * Useful for testing that business-logic code correctly rejects calls that are\n * made outside a tenant context.\n *\n * @param fn - Async function that should throw `TenantContextError`.\n * @param messageContains - Optional substring the error message must include.\n *\n * @example\n * ```typescript\n * await assertTenantContextRequired(async () => {\n * // No withTenant() in scope\n * await documentCollection.list({});\n * });\n * ```\n *\n * @see assertTenantIsolationViolation\n * @see TenantContextError\n */\nexport async function assertTenantContextRequired(\n fn: () => Promise<unknown>,\n messageContains?: string,\n): Promise<void> {\n try {\n await fn();\n throw new Error('Expected TenantContextError but no error was thrown');\n } catch (error: unknown) {\n const err = error as Error & { code?: string };\n if (err.code !== 'TENANT_CONTEXT_REQUIRED') {\n throw new Error(\n `Expected TenantContextError but got ${err.constructor.name}: ${err.message}`,\n );\n }\n if (messageContains && !err.message.includes(messageContains)) {\n throw new Error(\n `Expected error message to contain '${messageContains}' but got: ${err.message}`,\n );\n }\n }\n}\n\n/**\n * Assert that executing `fn` throws a `TenantIsolationError`.\n *\n * Fails with a descriptive message if `fn` completes without throwing, or if\n * it throws a different error type. Optionally verifies that the error message\n * contains a specific substring.\n *\n * Use this to verify that cross-tenant data access attempts are correctly\n * blocked by the interceptor.\n *\n * @param fn - Async function that should throw `TenantIsolationError`.\n * @param messageContains - Optional substring the error message must include.\n *\n * @example\n * ```typescript\n * await withTenant({ tenantId: 'tenant-a' }, async () => {\n * await assertTenantIsolationViolation(async () => {\n * // Attempt to filter by a different tenant\n * await collection.list({ where: { tenantId: 'tenant-b' } });\n * });\n * });\n * ```\n *\n * @see assertTenantContextRequired\n * @see TenantIsolationError\n */\nexport async function assertTenantIsolationViolation(\n fn: () => Promise<unknown>,\n messageContains?: string,\n): Promise<void> {\n try {\n await fn();\n throw new Error('Expected TenantIsolationError but no error was thrown');\n } catch (error: unknown) {\n const err = error as Error & { code?: string };\n if (err.code !== 'TENANT_ISOLATION_VIOLATION') {\n throw new Error(\n `Expected TenantIsolationError but got ${err.constructor.name}: ${err.message}`,\n );\n }\n if (messageContains && !err.message.includes(messageContains)) {\n throw new Error(\n `Expected error message to contain '${messageContains}' but got: ${err.message}`,\n );\n }\n }\n}\n"],"mappings":";;;;AA6DA,IAAM,iBAAqC;CACzC,MAAM;CACN,OAAO;CACP,YAAY;CACZ,cAAc;CACd,uBAAuB;AACzB;AAGA,IAAM,sCAAsB,IAAI,IAAgC;AAwBzD,SAAS,0BACd,WACA,SAAsC,CAAC,GACjC;CACN,oBAAoB,IAAI,WAAW;EACjC,GAAG;EACH,GAAG;CACL,CAAC;AACH;AAaO,SAAS,4BAA4B,WAAyB;CACnE,oBAAoB,OAAO,SAAS;AACtC;AAYA,SAAS,kBAAkB,WAA2B;CACpD,MAAM,MAAM,UAAU,YAAY,GAAG;CACrC,OAAO,QAAQ,KAAK,YAAY,UAAU,MAAM,MAAM,CAAC;AACzD;AAQA,SAAS,YAAY,QA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