@happyvertical/smrt-tenancy 0.69.0 → 0.70.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/__smrt-register__.ts","../src/billing-relationship.ts","../src/fields.ts"],"sourcesContent":["// Generated by @happyvertical/smrt-core smrtPlugin at library build time.\n// The package manifest is inlined so self-registration cannot miss when a\n// downstream bundler relocates this module away from dist/manifest.json\n// (https://github.com/happyvertical/smrt/issues/1506,\n// https://github.com/happyvertical/smrt/issues/1507).\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\nObjectRegistry.registerPackageManifest(JSON.parse(\"{\\\"version\\\":\\\"1.0.0\\\",\\\"timestamp\\\":0,\\\"packageName\\\":\\\"@happyvertical/smrt-tenancy\\\",\\\"packageVersion\\\":\\\"0.69.0\\\",\\\"objects\\\":{\\\"@happyvertical/smrt-tenancy:BillingRelationship\\\":{\\\"name\\\":\\\"billingrelationship\\\",\\\"className\\\":\\\"BillingRelationship\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-tenancy:BillingRelationship\\\",\\\"collection\\\":\\\"billingrelationships\\\",\\\"filePath\\\":\\\"src/billing-relationship.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-tenancy\\\",\\\"fields\\\":{\\\"childTenantId\\\":{\\\"type\\\":\\\"crossPackageRef\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\",\\\"related\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\"},\\\"required\\\":true,\\\"related\\\":\\\"@happyvertical/smrt-users:Tenant\\\"},\\\"resellerTenantId\\\":{\\\"type\\\":\\\"crossPackageRef\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\",\\\"related\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"tenant-scope\\\"},\\\"required\\\":true,\\\"related\\\":\\\"@happyvertical/smrt-users:Tenant\\\"},\\\"billingOwnerMode\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"default\\\",\\\"enum\\\"]},\\\"required\\\":false,\\\"default\\\":\\\"self\\\",\\\"enum\\\":[\\\"self\\\",\\\"reseller\\\"]}},\\\"methods\\\":{},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_billing_relationships\\\",\\\"conflictColumns\\\":[\\\"child_tenant_id\\\"],\\\"api\\\":false,\\\"cli\\\":false,\\\"mcp\\\":false},\\\"extends\\\":\\\"SmrtObject\\\",\\\"exportName\\\":\\\"BillingRelationship\\\",\\\"collectionExportName\\\":\\\"BillingRelationshipCollection\\\",\\\"validationRules\\\":[{\\\"field\\\":\\\"childTenantId\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"crossPackageRef\\\"},{\\\"field\\\":\\\"resellerTenantId\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"crossPackageRef\\\"}],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_billing_relationships\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_billing_relationships\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"child_tenant_id\\\\\\\" UUID NOT NULL,\\\\n \\\\\\\"reseller_tenant_id\\\\\\\" UUID NOT NULL,\\\\n \\\\\\\"billing_owner_mode\\\\\\\" TEXT DEFAULT 'self'\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"child_tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"crossPackageRef\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"reseller_tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"crossPackageRef\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"billing_owner_mode\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false,\\\"default\\\":\\\"self\\\"}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_billing_relationships_child_tenant_id_idx\\\",\\\"columns\\\":[\\\"child_tenant_id\\\"],\\\"unique\\\":true},{\\\"name\\\":\\\"_smrt_billing_relationships_slug_context_idx\\\",\\\"columns\\\":[\\\"slug\\\",\\\"context\\\"]},{\\\"name\\\":\\\"_smrt_billing_relationships_created_at_idx\\\",\\\"columns\\\":[\\\"created_at\\\"]},{\\\"name\\\":\\\"_smrt_billing_relationships_reseller_tenant_id_idx\\\",\\\"columns\\\":[\\\"reseller_tenant_id\\\"]}],\\\"version\\\":\\\"549503f6\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-tenancy\\\"},\\\"@happyvertical/smrt-tenancy:BillingRelationshipCollection\\\":{\\\"name\\\":\\\"billingrelationshipcollection\\\",\\\"className\\\":\\\"BillingRelationshipCollection\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-tenancy:BillingRelationshipCollection\\\",\\\"collection\\\":\\\"billingrelationships\\\",\\\"filePath\\\":\\\"src/billing-relationship.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-tenancy\\\",\\\"fields\\\":{},\\\"methods\\\":{},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_billing_relationships\\\",\\\"api\\\":false,\\\"mcp\\\":false,\\\"cli\\\":false},\\\"extends\\\":\\\"SmrtCollection\\\",\\\"extendsTypeArg\\\":\\\"BillingRelationship\\\",\\\"exportName\\\":\\\"BillingRelationshipCollection\\\",\\\"collectionExportName\\\":\\\"BillingRelationshipCollectionCollection\\\",\\\"collectionOf\\\":\\\"@happyvertical/smrt-tenancy:BillingRelationship\\\",\\\"inheritedExposure\\\":[\\\"api\\\",\\\"mcp\\\",\\\"cli\\\"],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_billing_relationships\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_billing_relationships\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"child_tenant_id\\\\\\\" UUID NOT NULL,\\\\n \\\\\\\"reseller_tenant_id\\\\\\\" UUID NOT NULL,\\\\n \\\\\\\"billing_owner_mode\\\\\\\" TEXT DEFAULT 'self'\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"child_tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"crossPackageRef\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"reseller_tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"crossPackageRef\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"billing_owner_mode\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false,\\\"default\\\":\\\"self\\\"}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_billing_relationships_child_tenant_id_idx\\\",\\\"columns\\\":[\\\"child_tenant_id\\\"],\\\"unique\\\":true},{\\\"name\\\":\\\"_smrt_billing_relationships_slug_context_idx\\\",\\\"columns\\\":[\\\"slug\\\",\\\"context\\\"]},{\\\"name\\\":\\\"_smrt_billing_relationships_created_at_idx\\\",\\\"columns\\\":[\\\"created_at\\\"]},{\\\"name\\\":\\\"_smrt_billing_relationships_reseller_tenant_id_idx\\\",\\\"columns\\\":[\\\"reseller_tenant_id\\\"]}],\\\"version\\\":\\\"549503f6\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-tenancy\\\"}},\\\"moduleType\\\":\\\"smrt\\\",\\\"smrtDependencies\\\":[\\\"@happyvertical/smrt-core\\\"],\\\"browser\\\":{\\\"status\\\":\\\"server-only\\\",\\\"issues\\\":[\\\"#3624\\\"],\\\"reason\\\":\\\"node:async_hooks\\\"},\\\"stampsConstructors\\\":true}\"));\n","/** Reseller parentage and billing ownership, independent of user permissions. */\nimport {\n crossPackageRef,\n field,\n isEmbeddedDatabase,\n isPostgresDatabase,\n type SmrtClassOptions,\n SmrtCollection,\n SmrtObject,\n smrt,\n withEmbeddedWriteTransaction,\n} from '@happyvertical/smrt-core';\nimport {\n getTenantId,\n isSuperAdminBypass,\n isSystemContext,\n TenantIsolationError,\n} from './context.js';\n\nexport type BillingOwnerMode = 'self' | 'reseller';\n\nexport interface BillingRelationshipView {\n childTenantId: string;\n resellerTenantId: string;\n billingOwnerMode: BillingOwnerMode;\n billingOwnerTenantId: string;\n}\n\nexport type BillingRelationshipAction = 'read' | 'manage';\n\nexport interface BillingRelationshipServiceOptions extends SmrtClassOptions {\n /** Resolve tenant IDs against the host tenant directory. */\n tenantExists: (tenantId: string) => Promise<boolean>;\n /** Optional host permission check for access beyond the built-in context rules. */\n authorize?: (request: {\n action: BillingRelationshipAction;\n childTenantId: string;\n resellerTenantId?: string;\n }) => Promise<boolean>;\n}\n\nexport class BillingRelationshipError extends Error {\n constructor(\n message: string,\n public readonly code:\n | 'INVALID_TENANT'\n | 'INVALID_OWNER_MODE'\n | 'TENANT_NOT_FOUND'\n | 'CIRCULAR_RELATIONSHIP',\n ) {\n super(message);\n this.name = 'BillingRelationshipError';\n }\n}\n\n@smrt({\n tableName: '_smrt_billing_relationships',\n conflictColumns: ['child_tenant_id'],\n api: false,\n cli: false,\n mcp: false,\n})\nexport class BillingRelationship extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-tenancy\";\n @crossPackageRef('@happyvertical/smrt-users:Tenant')\n @field({ required: true, requiredFor: 'identity' })\n childTenantId: string = '';\n @crossPackageRef('@happyvertical/smrt-users:Tenant')\n @field({ required: true, requiredFor: 'tenant-scope' })\n resellerTenantId: string = '';\n billingOwnerMode: BillingOwnerMode = 'self';\n\n protected async validateBeforeSave(): Promise<void> {\n await super.validateBeforeSave();\n this.childTenantId = canonicalTenantId(this.childTenantId);\n this.resellerTenantId = canonicalTenantId(this.resellerTenantId);\n assertMode(this.billingOwnerMode);\n if (this.childTenantId === this.resellerTenantId) {\n throw new BillingRelationshipError(\n 'A tenant cannot resell to itself.',\n 'CIRCULAR_RELATIONSHIP',\n );\n }\n }\n}\n\nexport class BillingRelationshipCollection extends SmrtCollection<BillingRelationship> {\n static readonly _itemClass = BillingRelationship;\n}\n\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction assertTenantId(id: string): void {\n if (typeof id !== 'string' || !UUID_PATTERN.test(id)) {\n throw new BillingRelationshipError(\n 'Tenant IDs must be UUIDs.',\n 'INVALID_TENANT',\n );\n }\n}\n\nfunction canonicalTenantId(id: string): string {\n assertTenantId(id);\n return id.toLowerCase();\n}\n\nfunction assertMode(mode: BillingOwnerMode): void {\n if (mode !== 'self' && mode !== 'reseller') {\n throw new BillingRelationshipError(\n 'Billing owner mode must be self or reseller.',\n 'INVALID_OWNER_MODE',\n );\n }\n}\n\nfunction view(row: BillingRelationship): BillingRelationshipView {\n const childTenantId = canonicalTenantId(row.childTenantId);\n const resellerTenantId = canonicalTenantId(row.resellerTenantId);\n assertMode(row.billingOwnerMode);\n return {\n childTenantId,\n resellerTenantId,\n billingOwnerMode: row.billingOwnerMode,\n billingOwnerTenantId:\n row.billingOwnerMode === 'reseller' ? resellerTenantId : childTenantId,\n };\n}\n\n/**\n * The one-row-per-child billing graph. The host supplies tenant existence and\n * any additional authorization; absent a host authorizer, only an explicit\n * system context can mutate relationships.\n */\nexport class BillingRelationshipService {\n private constructor(\n private readonly relationships: BillingRelationshipCollection,\n private readonly options: BillingRelationshipServiceOptions,\n ) {}\n\n static async create(\n options: BillingRelationshipServiceOptions,\n ): Promise<BillingRelationshipService> {\n if (typeof options.tenantExists !== 'function') {\n throw new Error('Billing relationships require a tenantExists resolver.');\n }\n const relationships = await BillingRelationshipCollection.create(options);\n if (/^(?:https?|libsql):\\/\\//iu.test(relationships.db.url ?? '')) {\n throw new Error(\n 'Billing relationships require a local SQL or PostgreSQL database with serialized transactions.',\n );\n }\n if (!relationships.db.transaction) {\n throw new Error('Billing relationships require database transactions.');\n }\n return new BillingRelationshipService(relationships, options);\n }\n\n /** A tenant without a relationship always pays for itself. */\n async resolveBillingOwner(childTenantId: string): Promise<string> {\n childTenantId = canonicalTenantId(childTenantId);\n const row = await this.relationships.get({ childTenantId });\n await this.assertReadable(childTenantId, row?.resellerTenantId);\n await this.assertExists(childTenantId);\n if (row) await this.assertExists(row.resellerTenantId);\n return row ? view(row).billingOwnerTenantId : childTenantId;\n }\n\n async getRelationship(\n childTenantId: string,\n ): Promise<BillingRelationshipView | null> {\n childTenantId = canonicalTenantId(childTenantId);\n const row = await this.relationships.get({ childTenantId });\n await this.assertReadable(childTenantId, row?.resellerTenantId);\n await this.assertExists(childTenantId);\n if (row) await this.assertExists(row.resellerTenantId);\n return row ? view(row) : null;\n }\n\n /** List direct children billed to an owner, with no collection page limit. */\n async listChildrenBilledTo(ownerTenantId: string): Promise<string[]> {\n ownerTenantId = canonicalTenantId(ownerTenantId);\n await this.assertReadable(ownerTenantId);\n await this.assertExists(ownerTenantId);\n const result = await this.relationships.db.query(\n 'SELECT child_tenant_id FROM _smrt_billing_relationships WHERE reseller_tenant_id = ? AND billing_owner_mode = ? ORDER BY child_tenant_id',\n ownerTenantId,\n 'reseller',\n );\n return result.rows.map((row) => {\n return canonicalTenantId(String(row.child_tenant_id));\n });\n }\n\n /** Create or replace parentage and its default billing owner in one row. */\n async setRelationship(input: {\n childTenantId: string;\n resellerTenantId: string;\n billingOwnerMode: BillingOwnerMode;\n }): Promise<BillingRelationshipView> {\n const childTenantId = canonicalTenantId(input.childTenantId);\n const resellerTenantId = canonicalTenantId(input.resellerTenantId);\n const { billingOwnerMode } = input;\n assertMode(billingOwnerMode);\n await this.assertManage(childTenantId, resellerTenantId);\n await this.assertExists(childTenantId);\n await this.assertExists(resellerTenantId);\n if (childTenantId === resellerTenantId) {\n throw new BillingRelationshipError(\n 'A tenant cannot resell to itself.',\n 'CIRCULAR_RELATIONSHIP',\n );\n }\n return withEmbeddedWriteTransaction(\n this.relationships.db,\n isEmbeddedDatabase(this.relationships.db),\n async (db) => {\n if (isPostgresDatabase(db)) {\n await db.query(\n \"SELECT pg_advisory_xact_lock(hashtext('smrt-billing-relationships'))\",\n );\n }\n const relationships = await BillingRelationshipCollection.create({\n db,\n });\n await this.assertAcyclic(\n relationships,\n childTenantId,\n resellerTenantId,\n );\n const existing = await relationships.get({ childTenantId });\n if (existing && existing.resellerTenantId !== resellerTenantId) {\n await this.assertManage(childTenantId, existing.resellerTenantId);\n }\n const row = existing\n ? Object.assign(existing, { resellerTenantId, billingOwnerMode })\n : await relationships.create({\n childTenantId,\n resellerTenantId,\n billingOwnerMode,\n });\n if (existing) await row.save();\n return view(row);\n },\n );\n }\n\n /** Remove reseller parentage. The child becomes self-billed. */\n async clearRelationship(childTenantId: string): Promise<void> {\n childTenantId = canonicalTenantId(childTenantId);\n await withEmbeddedWriteTransaction(\n this.relationships.db,\n isEmbeddedDatabase(this.relationships.db),\n async (db) => {\n if (isPostgresDatabase(db)) {\n await db.query(\n \"SELECT pg_advisory_xact_lock(hashtext('smrt-billing-relationships'))\",\n );\n }\n const relationships = await BillingRelationshipCollection.create({\n db,\n });\n const current = await relationships.get({ childTenantId });\n await this.assertManage(childTenantId, current?.resellerTenantId);\n if (current?.id) {\n // SmrtObject.delete() starts its own cascade transaction, which\n // DuckDB cannot nest. This row has no dependents, so delete it on\n // the already-bound transaction handle.\n await db.delete('_smrt_billing_relationships', { id: current.id });\n }\n },\n );\n }\n\n private async assertAcyclic(\n relationships: BillingRelationshipCollection,\n childTenantId: string,\n resellerTenantId: string,\n ): Promise<void> {\n const visited = new Set([childTenantId]);\n let cursor: string | undefined = resellerTenantId;\n while (cursor) {\n if (visited.has(cursor)) {\n throw new BillingRelationshipError(\n 'Reseller relationships cannot form a cycle.',\n 'CIRCULAR_RELATIONSHIP',\n );\n }\n visited.add(cursor);\n const row = await relationships.get({ childTenantId: cursor });\n cursor = row ? canonicalTenantId(row.resellerTenantId) : undefined;\n }\n }\n\n private async assertExists(tenantId: string): Promise<void> {\n assertTenantId(tenantId);\n if (!(await this.options.tenantExists(tenantId))) {\n throw new BillingRelationshipError(\n `Tenant not found: ${tenantId}`,\n 'TENANT_NOT_FOUND',\n );\n }\n }\n\n private async assertReadable(\n childTenantId: string,\n resellerTenantId?: string,\n ): Promise<void> {\n if (\n isSystemContext() ||\n isSuperAdminBypass() ||\n getTenantId()?.toLowerCase() === childTenantId ||\n (resellerTenantId && getTenantId()?.toLowerCase() === resellerTenantId) ||\n (await this.options.authorize?.({\n action: 'read',\n childTenantId,\n resellerTenantId,\n }))\n ) {\n return;\n }\n throw new TenantIsolationError('Billing relationship access denied.');\n }\n\n private async assertManage(\n childTenantId: string,\n resellerTenantId?: string,\n ): Promise<void> {\n if (\n isSystemContext() ||\n isSuperAdminBypass() ||\n (await this.options.authorize?.({\n action: 'manage',\n childTenantId,\n resellerTenantId,\n }))\n ) {\n return;\n }\n throw new TenantIsolationError('Billing relationship mutation denied.');\n }\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"],"mappings":";;;;;;;AAOA,eAAe,wBAAwB,KAAK,MAAM,mqLAAuzM,CAAC;;;;;;;;;;;;;;;;;;ACkCn2M,IAAM,2BAAN,cAAuC,MAAM;CAClD,YACE,SACgB,MAKhB;EACA,MAAM,OAAO;EANG,KAAA,OAAA;EAOhB,KAAK,OAAO;CACd;CARkB;AASpB;AASO,IAAM,sBAAN,cAAkC,WAAW;CAGlD,gBAAwB;CAGxB,mBAA2B;CAC3B,mBAAqC;CAErC,MAAgB,qBAAoC;EAClD,MAAM,MAAM,mBAAmB;EAC/B,KAAK,gBAAgB,kBAAkB,KAAK,aAAa;EACzD,KAAK,mBAAmB,kBAAkB,KAAK,gBAAgB;EAC/D,WAAW,KAAK,gBAAgB;EAChC,IAAI,KAAK,kBAAkB,KAAK,kBAC9B,MAAM,IAAI,yBACR,qCACA,uBACF;CAEJ;AACF;AArBsD,cAAzC,qBAAgD,mBAAkB,6BAAA;AAG7E,gBAAA,CAFC,gBAAgB,kCAAkC,GAClD,MAAM;CAAE,UAAU;CAAM,aAAa;AAAW,CAAC,CAAA,GAFvC,oBAGX,WAAA,iBAAA,CAAA;AAGA,gBAAA,CAFC,gBAAgB,k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AAc,IAAI,EAAE,eAAe,OAAO,CAAC;GAC7D,SAAS,MAAM,kBAAkB,IAAI,gBAAgB,IAAI,KAAA;EAC3D;CACF;CAEA,MAAc,aAAa,UAAiC;EAC1D,eAAe,QAAQ;EACvB,IAAI,CAAE,MAAM,KAAK,QAAQ,aAAa,QAAQ,GAC5C,MAAM,IAAI,yBACR,qBAAqB,YACrB,kBACF;CAEJ;CAEA,MAAc,eACZ,eACA,kBACe;EACf,IACE,gBAAgB,KAChB,mBAAmB,KACnB,YAAY,CAAA,EAAG,YAAY,MAAM,iBAChC,oBAAoB,YAAY,CAAA,EAAG,YAAY,MAAM,oBACrD,MAAM,KAAK,QAAQ,YAAY;GAC9B,QAAQ;GACR;GACA;EACF,CAAC,GAED;EAEF,MAAM,IAAI,qBAAqB,qCAAqC;CACtE;CAEA,MAAc,aACZ,eACA,kBACe;EACf,IACE,gBAAgB,KAChB,mBAAmB,KAClB,MAAM,KAAK,QAAQ,YAAY;GAC9B,QAAQ;GACR;GACA;EACF,CAAC,GAED;EAEF,MAAM,IAAI,qBAAqB,uCAAuC;CACxE;AACF;;;ACvPO,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"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/__smrt-register__.ts","../src/billing-relationship.ts","../src/fields.ts"],"sourcesContent":["// Generated by @happyvertical/smrt-core smrtPlugin at library build time.\n// The package manifest is inlined so self-registration cannot miss when a\n// downstream bundler relocates this module away from dist/manifest.json\n// (https://github.com/happyvertical/smrt/issues/1506,\n// https://github.com/happyvertical/smrt/issues/1507).\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\nObjectRegistry.registerPackageManifest(JSON.parse(\"{\\\"version\\\":\\\"1.0.0\\\",\\\"timestamp\\\":0,\\\"packageName\\\":\\\"@happyvertical/smrt-tenancy\\\",\\\"packageVersion\\\":\\\"0.70.1\\\",\\\"objects\\\":{\\\"@happyvertical/smrt-tenancy:BillingRelationship\\\":{\\\"name\\\":\\\"billingrelationship\\\",\\\"className\\\":\\\"BillingRelationship\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-tenancy:BillingRelationship\\\",\\\"collection\\\":\\\"billingrelationships\\\",\\\"filePath\\\":\\\"src/billing-relationship.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-tenancy\\\",\\\"fields\\\":{\\\"childTenantId\\\":{\\\"type\\\":\\\"crossPackageRef\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\",\\\"related\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\"},\\\"required\\\":true,\\\"related\\\":\\\"@happyvertical/smrt-users:Tenant\\\"},\\\"resellerTenantId\\\":{\\\"type\\\":\\\"crossPackageRef\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\",\\\"related\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"tenant-scope\\\"},\\\"required\\\":true,\\\"related\\\":\\\"@happyvertical/smrt-users:Tenant\\\"},\\\"billingOwnerMode\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"default\\\",\\\"enum\\\"]},\\\"required\\\":false,\\\"default\\\":\\\"self\\\",\\\"enum\\\":[\\\"self\\\",\\\"reseller\\\"]}},\\\"methods\\\":{},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_billing_relationships\\\",\\\"conflictColumns\\\":[\\\"child_tenant_id\\\"],\\\"api\\\":false,\\\"cli\\\":false,\\\"mcp\\\":false},\\\"extends\\\":\\\"SmrtObject\\\",\\\"exportName\\\":\\\"BillingRelationship\\\",\\\"collectionExportName\\\":\\\"BillingRelationshipCollection\\\",\\\"validationRules\\\":[{\\\"field\\\":\\\"childTenantId\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"crossPackageRef\\\"},{\\\"field\\\":\\\"resellerTenantId\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"crossPackageRef\\\"}],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_billing_relationships\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_billing_relationships\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"child_tenant_id\\\\\\\" UUID NOT NULL,\\\\n \\\\\\\"reseller_tenant_id\\\\\\\" UUID NOT NULL,\\\\n \\\\\\\"billing_owner_mode\\\\\\\" TEXT DEFAULT 'self'\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"child_tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"crossPackageRef\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"reseller_tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"crossPackageRef\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"billing_owner_mode\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false,\\\"default\\\":\\\"self\\\"}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_billing_relationships_child_tenant_id_idx\\\",\\\"columns\\\":[\\\"child_tenant_id\\\"],\\\"unique\\\":true},{\\\"name\\\":\\\"_smrt_billing_relationships_slug_context_idx\\\",\\\"columns\\\":[\\\"slug\\\",\\\"context\\\"]},{\\\"name\\\":\\\"_smrt_billing_relationships_created_at_idx\\\",\\\"columns\\\":[\\\"created_at\\\"]},{\\\"name\\\":\\\"_smrt_billing_relationships_reseller_tenant_id_idx\\\",\\\"columns\\\":[\\\"reseller_tenant_id\\\"]}],\\\"version\\\":\\\"549503f6\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-tenancy\\\"},\\\"@happyvertical/smrt-tenancy:BillingRelationshipCollection\\\":{\\\"name\\\":\\\"billingrelationshipcollection\\\",\\\"className\\\":\\\"BillingRelationshipCollection\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-tenancy:BillingRelationshipCollection\\\",\\\"collection\\\":\\\"billingrelationships\\\",\\\"filePath\\\":\\\"src/billing-relationship.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-tenancy\\\",\\\"fields\\\":{},\\\"methods\\\":{},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_billing_relationships\\\",\\\"api\\\":false,\\\"mcp\\\":false,\\\"cli\\\":false},\\\"extends\\\":\\\"SmrtCollection\\\",\\\"extendsTypeArg\\\":\\\"BillingRelationship\\\",\\\"exportName\\\":\\\"BillingRelationshipCollection\\\",\\\"collectionExportName\\\":\\\"BillingRelationshipCollectionCollection\\\",\\\"collectionOf\\\":\\\"@happyvertical/smrt-tenancy:BillingRelationship\\\",\\\"inheritedExposure\\\":[\\\"api\\\",\\\"mcp\\\",\\\"cli\\\"],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_billing_relationships\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_billing_relationships\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"child_tenant_id\\\\\\\" UUID NOT NULL,\\\\n \\\\\\\"reseller_tenant_id\\\\\\\" UUID NOT NULL,\\\\n \\\\\\\"billing_owner_mode\\\\\\\" TEXT DEFAULT 'self'\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"child_tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"crossPackageRef\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"reseller_tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"crossPackageRef\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"billing_owner_mode\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false,\\\"default\\\":\\\"self\\\"}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_billing_relationships_child_tenant_id_idx\\\",\\\"columns\\\":[\\\"child_tenant_id\\\"],\\\"unique\\\":true},{\\\"name\\\":\\\"_smrt_billing_relationships_slug_context_idx\\\",\\\"columns\\\":[\\\"slug\\\",\\\"context\\\"]},{\\\"name\\\":\\\"_smrt_billing_relationships_created_at_idx\\\",\\\"columns\\\":[\\\"created_at\\\"]},{\\\"name\\\":\\\"_smrt_billing_relationships_reseller_tenant_id_idx\\\",\\\"columns\\\":[\\\"reseller_tenant_id\\\"]}],\\\"version\\\":\\\"549503f6\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-tenancy\\\"}},\\\"moduleType\\\":\\\"smrt\\\",\\\"smrtDependencies\\\":[\\\"@happyvertical/smrt-core\\\"],\\\"browser\\\":{\\\"status\\\":\\\"server-only\\\",\\\"issues\\\":[\\\"#3624\\\"],\\\"reason\\\":\\\"node:async_hooks\\\"},\\\"stampsConstructors\\\":true}\"));\n","/** Reseller parentage and billing ownership, independent of user permissions. */\nimport {\n crossPackageRef,\n field,\n isEmbeddedDatabase,\n isPostgresDatabase,\n type SmrtClassOptions,\n SmrtCollection,\n SmrtObject,\n smrt,\n withEmbeddedWriteTransaction,\n} from '@happyvertical/smrt-core';\nimport {\n getTenantId,\n isSuperAdminBypass,\n isSystemContext,\n TenantIsolationError,\n} from './context.js';\n\nexport type BillingOwnerMode = 'self' | 'reseller';\n\nexport interface BillingRelationshipView {\n childTenantId: string;\n resellerTenantId: string;\n billingOwnerMode: BillingOwnerMode;\n billingOwnerTenantId: string;\n}\n\nexport type BillingRelationshipAction = 'read' | 'manage';\n\nexport interface BillingRelationshipServiceOptions extends SmrtClassOptions {\n /** Resolve tenant IDs against the host tenant directory. */\n tenantExists: (tenantId: string) => Promise<boolean>;\n /** Optional host permission check for access beyond the built-in context rules. */\n authorize?: (request: {\n action: BillingRelationshipAction;\n childTenantId: string;\n resellerTenantId?: string;\n }) => Promise<boolean>;\n}\n\nexport class BillingRelationshipError extends Error {\n constructor(\n message: string,\n public readonly code:\n | 'INVALID_TENANT'\n | 'INVALID_OWNER_MODE'\n | 'TENANT_NOT_FOUND'\n | 'CIRCULAR_RELATIONSHIP',\n ) {\n super(message);\n this.name = 'BillingRelationshipError';\n }\n}\n\n@smrt({\n tableName: '_smrt_billing_relationships',\n conflictColumns: ['child_tenant_id'],\n api: false,\n cli: false,\n mcp: false,\n})\nexport class BillingRelationship extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-tenancy\";\n @crossPackageRef('@happyvertical/smrt-users:Tenant')\n @field({ required: true, requiredFor: 'identity' })\n childTenantId: string = '';\n @crossPackageRef('@happyvertical/smrt-users:Tenant')\n @field({ required: true, requiredFor: 'tenant-scope' })\n resellerTenantId: string = '';\n billingOwnerMode: BillingOwnerMode = 'self';\n\n protected async validateBeforeSave(): Promise<void> {\n await super.validateBeforeSave();\n this.childTenantId = canonicalTenantId(this.childTenantId);\n this.resellerTenantId = canonicalTenantId(this.resellerTenantId);\n assertMode(this.billingOwnerMode);\n if (this.childTenantId === this.resellerTenantId) {\n throw new BillingRelationshipError(\n 'A tenant cannot resell to itself.',\n 'CIRCULAR_RELATIONSHIP',\n );\n }\n }\n}\n\nexport class BillingRelationshipCollection extends SmrtCollection<BillingRelationship> {\n static readonly _itemClass = BillingRelationship;\n}\n\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction assertTenantId(id: string): void {\n if (typeof id !== 'string' || !UUID_PATTERN.test(id)) {\n throw new BillingRelationshipError(\n 'Tenant IDs must be UUIDs.',\n 'INVALID_TENANT',\n );\n }\n}\n\nfunction canonicalTenantId(id: string): string {\n assertTenantId(id);\n return id.toLowerCase();\n}\n\nfunction assertMode(mode: BillingOwnerMode): void {\n if (mode !== 'self' && mode !== 'reseller') {\n throw new BillingRelationshipError(\n 'Billing owner mode must be self or reseller.',\n 'INVALID_OWNER_MODE',\n );\n }\n}\n\nfunction view(row: BillingRelationship): BillingRelationshipView {\n const childTenantId = canonicalTenantId(row.childTenantId);\n const resellerTenantId = canonicalTenantId(row.resellerTenantId);\n assertMode(row.billingOwnerMode);\n return {\n childTenantId,\n resellerTenantId,\n billingOwnerMode: row.billingOwnerMode,\n billingOwnerTenantId:\n row.billingOwnerMode === 'reseller' ? resellerTenantId : childTenantId,\n };\n}\n\n/**\n * The one-row-per-child billing graph. The host supplies tenant existence and\n * any additional authorization; absent a host authorizer, only an explicit\n * system context can mutate relationships.\n */\nexport class BillingRelationshipService {\n private constructor(\n private readonly relationships: BillingRelationshipCollection,\n private readonly options: BillingRelationshipServiceOptions,\n ) {}\n\n static async create(\n options: BillingRelationshipServiceOptions,\n ): Promise<BillingRelationshipService> {\n if (typeof options.tenantExists !== 'function') {\n throw new Error('Billing relationships require a tenantExists resolver.');\n }\n const relationships = await BillingRelationshipCollection.create(options);\n if (/^(?:https?|libsql):\\/\\//iu.test(relationships.db.url ?? '')) {\n throw new Error(\n 'Billing relationships require a local SQL or PostgreSQL database with serialized transactions.',\n );\n }\n if (!relationships.db.transaction) {\n throw new Error('Billing relationships require database transactions.');\n }\n return new BillingRelationshipService(relationships, options);\n }\n\n /** A tenant without a relationship always pays for itself. */\n async resolveBillingOwner(childTenantId: string): Promise<string> {\n childTenantId = canonicalTenantId(childTenantId);\n const row = await this.relationships.get({ childTenantId });\n await this.assertReadable(childTenantId, row?.resellerTenantId);\n await this.assertExists(childTenantId);\n if (row) await this.assertExists(row.resellerTenantId);\n return row ? view(row).billingOwnerTenantId : childTenantId;\n }\n\n async getRelationship(\n childTenantId: string,\n ): Promise<BillingRelationshipView | null> {\n childTenantId = canonicalTenantId(childTenantId);\n const row = await this.relationships.get({ childTenantId });\n await this.assertReadable(childTenantId, row?.resellerTenantId);\n await this.assertExists(childTenantId);\n if (row) await this.assertExists(row.resellerTenantId);\n return row ? view(row) : null;\n }\n\n /** List direct children billed to an owner, with no collection page limit. */\n async listChildrenBilledTo(ownerTenantId: string): Promise<string[]> {\n ownerTenantId = canonicalTenantId(ownerTenantId);\n await this.assertReadable(ownerTenantId);\n await this.assertExists(ownerTenantId);\n const result = await this.relationships.db.query(\n 'SELECT child_tenant_id FROM _smrt_billing_relationships WHERE reseller_tenant_id = ? AND billing_owner_mode = ? ORDER BY child_tenant_id',\n ownerTenantId,\n 'reseller',\n );\n return result.rows.map((row) => {\n return canonicalTenantId(String(row.child_tenant_id));\n });\n }\n\n /** Create or replace parentage and its default billing owner in one row. */\n async setRelationship(input: {\n childTenantId: string;\n resellerTenantId: string;\n billingOwnerMode: BillingOwnerMode;\n }): Promise<BillingRelationshipView> {\n const childTenantId = canonicalTenantId(input.childTenantId);\n const resellerTenantId = canonicalTenantId(input.resellerTenantId);\n const { billingOwnerMode } = input;\n assertMode(billingOwnerMode);\n await this.assertManage(childTenantId, resellerTenantId);\n await this.assertExists(childTenantId);\n await this.assertExists(resellerTenantId);\n if (childTenantId === resellerTenantId) {\n throw new BillingRelationshipError(\n 'A tenant cannot resell to itself.',\n 'CIRCULAR_RELATIONSHIP',\n );\n }\n return withEmbeddedWriteTransaction(\n this.relationships.db,\n isEmbeddedDatabase(this.relationships.db),\n async (db) => {\n if (isPostgresDatabase(db)) {\n await db.query(\n \"SELECT pg_advisory_xact_lock(hashtext('smrt-billing-relationships'))\",\n );\n }\n const relationships = await BillingRelationshipCollection.create({\n db,\n });\n await this.assertAcyclic(\n relationships,\n childTenantId,\n resellerTenantId,\n );\n const existing = await relationships.get({ childTenantId });\n if (existing && existing.resellerTenantId !== resellerTenantId) {\n await this.assertManage(childTenantId, existing.resellerTenantId);\n }\n const row = existing\n ? Object.assign(existing, { resellerTenantId, billingOwnerMode })\n : await relationships.create({\n childTenantId,\n resellerTenantId,\n billingOwnerMode,\n });\n if (existing) await row.save();\n return view(row);\n },\n );\n }\n\n /** Remove reseller parentage. The child becomes self-billed. */\n async clearRelationship(childTenantId: string): Promise<void> {\n childTenantId = canonicalTenantId(childTenantId);\n await withEmbeddedWriteTransaction(\n this.relationships.db,\n isEmbeddedDatabase(this.relationships.db),\n async (db) => {\n if (isPostgresDatabase(db)) {\n await db.query(\n \"SELECT pg_advisory_xact_lock(hashtext('smrt-billing-relationships'))\",\n );\n }\n const relationships = await BillingRelationshipCollection.create({\n db,\n });\n const current = await relationships.get({ childTenantId });\n await this.assertManage(childTenantId, current?.resellerTenantId);\n if (current?.id) {\n // SmrtObject.delete() starts its own cascade transaction, which\n // DuckDB cannot nest. This row has no dependents, so delete it on\n // the already-bound transaction handle.\n await db.delete('_smrt_billing_relationships', { id: current.id });\n }\n },\n );\n }\n\n private async assertAcyclic(\n relationships: BillingRelationshipCollection,\n childTenantId: string,\n resellerTenantId: string,\n ): Promise<void> {\n const visited = new Set([childTenantId]);\n let cursor: string | undefined = resellerTenantId;\n while (cursor) {\n if (visited.has(cursor)) {\n throw new BillingRelationshipError(\n 'Reseller relationships cannot form a cycle.',\n 'CIRCULAR_RELATIONSHIP',\n );\n }\n visited.add(cursor);\n const row = await relationships.get({ childTenantId: cursor });\n cursor = row ? canonicalTenantId(row.resellerTenantId) : undefined;\n }\n }\n\n private async assertExists(tenantId: string): Promise<void> {\n assertTenantId(tenantId);\n if (!(await this.options.tenantExists(tenantId))) {\n throw new BillingRelationshipError(\n `Tenant not found: ${tenantId}`,\n 'TENANT_NOT_FOUND',\n );\n }\n }\n\n private async assertReadable(\n childTenantId: string,\n resellerTenantId?: string,\n ): Promise<void> {\n if (\n isSystemContext() ||\n isSuperAdminBypass() ||\n getTenantId()?.toLowerCase() === childTenantId ||\n (resellerTenantId && getTenantId()?.toLowerCase() === resellerTenantId) ||\n (await this.options.authorize?.({\n action: 'read',\n childTenantId,\n resellerTenantId,\n }))\n ) {\n return;\n }\n throw new TenantIsolationError('Billing relationship access denied.');\n }\n\n private async assertManage(\n childTenantId: string,\n resellerTenantId?: string,\n ): Promise<void> {\n if (\n isSystemContext() ||\n isSuperAdminBypass() ||\n (await this.options.authorize?.({\n action: 'manage',\n childTenantId,\n resellerTenantId,\n }))\n ) {\n return;\n }\n throw new TenantIsolationError('Billing relationship mutation denied.');\n }\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 };\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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;AAyHD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,GAAE,wBAA6B,GACrC,qBAAqB,CAoiBvB;AAiDD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,aAAa,CAAC,OAAO,GAAE,wBAA6B,GAAG,IAAI,CA6E1E;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,cAAc,IAAI,IAAI,CAuBrC;AAED;;;;;;;;;GASG;AACH,OAAO,EAAE,gBAAgB,EAAE,CAAC"}
@@ -2,7 +2,7 @@
2
2
  "version": "1.0.0",
3
3
  "timestamp": 0,
4
4
  "packageName": "@happyvertical/smrt-tenancy",
5
- "packageVersion": "0.69.0",
5
+ "packageVersion": "0.70.1",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-tenancy:BillingRelationship": {
8
8
  "name": "billingrelationship",
@@ -1 +1 @@
1
- {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAOH;;;;;;;;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,EAA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,EAAE,OAAO,GAAG,SAAS,GAAG,MAAM,CAAC;IACvC,OAAO,EAAE,MAAM,CAAC;CACjB;AAyGD;;;;;;;;GAQG;AACH,wBAAgB,8BAA8B,IAAI,yBAAyB,EAAE,CAS5E"}
@@ -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.69.0",
6
+ "packageVersion": "0.70.1",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "b5480e867a5247138594daec14010245287b29917cdd7b253bba014d75c3e27d",
11
- "packageJson": "33543ec819ff818839a946d8850d9d5b1000d0e12c8858cece347bdef2d3e2fa",
12
- "agents": "683f0c09408d9216ed364e9588e88475459b93bb9e84cc726fadc2848d3aad65"
10
+ "manifest": "fc4d94790ecd9b63370f39ee3a027ec6b1db965d01636cab7296f315ad357026",
11
+ "packageJson": "1f4c6fcc35911e1423c91152a586eddf892e81e8cee3b63f78460760a07f4800",
12
+ "agents": "5735b8eea622e789bce0a30ba97f0546df9931bded8e85b3ffd16326a302aa98"
13
13
  },
14
14
  "exports": [
15
15
  ".",
@@ -150,7 +150,7 @@
150
150
  "polymorphicAssociations": 0,
151
151
  "uuidColumns": 6
152
152
  },
153
- "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## Billing relationships (#3058)\n\n`src/billing-relationship.ts` owns a separate reseller parent graph. It never\nupdates `smrt-users` `Tenant.parentTenantId` or tenant-scoped records. One row\nper child stores the reseller and `self`/`reseller` owner mode; owner queries\nderive one tenant ID. Mutations go through `BillingRelationshipService`, which\nserializes graph writes and rejects cycles. The host supplies tenant existence\nand optional authorization; no generated write surface is exposed. The model\nstays a root export because generated consumer registration imports every\npublic non-collection manifest object from the root; withholding it breaks\nevery dependent's `register.js` (publish dry run, smrt#3074). The collection\nstays unexported, as in smrt-chat. See the README for setup, access rules, and\nmigration guidance.\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\nThe tenant filter is recognised by the column a key resolves to, not by the\nliteral `tenantId` key. Filter keys are caller spelling (`tenant_id`,\n`TenantId`, `tenantId =` all resolve to the tenant column), so every hook that\nreads a filter (list in object and DNF form, get, the hierarchy read scope)\nfinds direct tenant filters with core's `resolveWhereKey()` and validates every\none present. Keys with an explicit non-equality operator are not direct\nfilters; the tenant predicate is added beside them. Core then refuses a record\nwith two keys for one column and operator, so the predicate this interceptor\nadds is never replaced. Any new code here that asks \"is the tenant already\nfiltered?\" must go through `directTenantFilterValues()`.\n\nWith a hierarchy read scope active, `beforeList` allows only its qualified model\nallowlist and bounds list-family reads to its tenant IDs (plus explicit NULL\nrows for catalogs). `beforeGet` retains the active-tenant predicate; neither hook\nhonors super-admin bypass inside the scope. Actor changes fail closed. `beforeSave`,\n`beforeDelete` and `beforeQuery` reject tenant-scoped operations, including raw\nquery opt-ins. The exported `runTenantHierarchyReadScope` is trusted owning-package\nplumbing, not an authorizer; hosts use the `smrt-users` `TenantCollection` wrappers.\nIt requires `enableTenancy()` and refuses nesting. See README \"Authorized hierarchy\nread scopes\" for bootstrap, RLS composition and the direct-database boundary.\n\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 forcing a `{ <ownership field>: null }` filter on list, count and point reads (runtime REST refuses such a caller every custom collection action), and emitted custom GET actions get the same keys in their options with every caller-sent ownership key (`tenantId` included) removed — the configured `field` (`@TenantScoped({ field: 'organizationId' })`), never a literal `tenantId` that may be an ordinary column, resolved at request time from the live registry so `registerTenantScopedClass()` at runtime is honoured (core's `applyWhereScope()`, which first drops every client filter on the ownership column under any spelling) 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. `enableTenancy()` also installs core's request tenant context hooks (`setRequestTenantContextHooks`), through which emitted routes of a runtime-registered model enter the caller's tenant (`enterRequestTenantContext` refuses a context without a tenant) and read the super-admin bypass per class (`allowSuperAdminBypass`, outside hierarchy read scopes, as the interceptor decides).\n\n**Optional-mode writes with no context pass through too, so generated routes refuse them.** The runtime REST server runs every operation on a tenant-scoped model through `runTenantScopedEntryPoint()` with the tenant its host supplies per request (`APIConfig.resolveTenant`); the generated SvelteKit CRUD, action and sync routes call `requireTenantWriteContext()` after reading the tenant from `locals`. A caller with no tenant gets 403 (401 if anonymous) for create, update, delete, a mutating action or a sync item, global rows included, unless the principal is explicitly cross-tenant (a system context, `allowCrossTenant`, or a verified super-admin bypass). Inside an active tenant context, `runTenantScopedEntryPoint()` refuses a caller that names a different tenant with `TenantIsolationError` (403, sync `forbidden`) and keeps the context for a caller that names none. Tests: `src/__tests__/rest-write-tenant-gate.test.ts`, `src/__tests__/rest-request-tenant.test.ts`.\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 (opted-in\n classes only) remain 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 of an\n opted-in class skip filtering but memory still keys to the active tenant\n (scoped tighter, not a 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 and lifts tenant enforcement (list/get filtering, raw-SQL policy, save/delete validation) **only for classes that opt in with `allowSuperAdminBypass: true`** (`@TenantScoped({ allowSuperAdminBypass: true })` or `@smrt({ tenantScoped: { allowSuperAdminBypass: true } })`). Every other tenant-scoped class — the flag defaults to `false` — stays scoped to the caller's tenant under bypass; unresolved config fails closed (#2973). Different from `withSystemContext()`, which removes context entirely and skips all checks. An active hierarchy read scope takes precedence: list/get remain bounded and tenant-scoped writes/raw queries reject.\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- **Runtime-only registration is audited, and ownership keys follow the field**: a class registered with `registerTenantScopedClass()` whose manifest declares no tenancy still gets the tenant-led default key when it has a `tenantId` field (core infers OWNERSHIP from the field, never the read policy). `auditTenantScopedRegistrations()` reports per selector: `missing_tenant_field` (error — neither the model nor a registered ancestor declares the field; an STI child registered before its manifest loads inherits it from the parent, #3623), `natural_key_not_tenant_scoped` (warning — an explicit key omits the tenant column, so a second tenant's same-key save is refused with `TENANT_ISOLATION_VIOLATION`), `undeclared_tenant_scope` (info). Registration (or first use, when it precedes core) logs the error/warning findings once. Core's save guard, not the interceptor, is what stops a tenant-filtered lookup from upserting onto another tenant's row (see 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\n## Portable model annotations (#4765)\n\nModel-only packages may import the original `TenantScoped`, `tenantId`, and\nannotation option types from `@happyvertical/smrt-tenancy/decorators`. This public\nentry reuses the same functions and registry as the root; it imports no context,\nAsyncLocalStorage, query helpers or adapters. It only declares metadata. Existing\nserver interception, context, filtering and RLS/authorization remain required and\nunchanged. Never replace these declarations with consumer-owned decorator stubs.\n",
153
+ "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## Billing relationships (#3058)\n\n`src/billing-relationship.ts` owns a separate reseller parent graph. It never\nupdates `smrt-users` `Tenant.parentTenantId` or tenant-scoped records. One row\nper child stores the reseller and `self`/`reseller` owner mode; owner queries\nderive one tenant ID. Mutations go through `BillingRelationshipService`, which\nserializes graph writes and rejects cycles. The host supplies tenant existence\nand optional authorization; no generated write surface is exposed. The model\nstays a root export because generated consumer registration imports every\npublic non-collection manifest object from the root; withholding it breaks\nevery dependent's `register.js` (publish dry run, smrt#3074). The collection\nstays unexported, as in smrt-chat. See the README for setup, access rules, and\nmigration guidance.\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\nThe tenant filter is recognised by the column a key resolves to, not by the\nliteral `tenantId` key. Filter keys are caller spelling (`tenant_id`,\n`TenantId`, `tenantId =` all resolve to the tenant column), so every hook that\nreads a filter (list in object and DNF form, get, the hierarchy read scope)\nfinds direct tenant filters with core's `resolveWhereKey()` and validates every\none present. Keys with an explicit non-equality operator are not direct\nfilters; the tenant predicate is added beside them. Core then refuses a record\nwith two keys for one column and operator, so the predicate this interceptor\nadds is never replaced. Any new code here that asks \"is the tenant already\nfiltered?\" must go through `directTenantFilterValues()`.\n\nWith a hierarchy read scope active, `beforeList` allows only its qualified model\nallowlist and bounds list-family reads to its tenant IDs (plus explicit NULL\nrows for catalogs). `beforeGet` retains the active-tenant predicate; neither hook\nhonors super-admin bypass inside the scope. Actor changes fail closed. `beforeSave`,\n`beforeDelete` and `beforeQuery` reject tenant-scoped operations, including raw\nquery opt-ins. The exported `runTenantHierarchyReadScope` is trusted owning-package\nplumbing, not an authorizer; hosts use the `smrt-users` `TenantCollection` wrappers.\nIt requires `enableTenancy()` and refuses nesting. See README \"Authorized hierarchy\nread scopes\" for bootstrap, RLS composition and the direct-database boundary.\n\n\n**Optional-mode reads with no context pass through UNFILTERED at the interceptor**, outside a request. That is intentional for trusted/admin call paths. Request paths (runtime REST, emitted routes, both sync apply paths, both MCP surfaces) resolve the request's tenancy in core (`src/request-tenancy.ts`, #5375) and bind it (runtime REST also refuses a caller with no tenant every custom collection action of a tenant-scoped model): core's `smrt-request-tenancy` interceptor (priority 110, before this one) holds every collection call of the request to rows without an owner (`{ <ownership field>: null }`, the configured `field`, never a literal `tenantId`) for a caller with no tenant, refuses a write by a caller with no tenant (rows without an owner included) or under a cross-tenant read grant, restricts the STI family table to the admitted types, decides every save and delete under the policy of the row's stored type and instance `_meta_type` (another policy than the class written through is refused, since this interceptor stamps and checks the owner under that class's policy) and, in an STI family with members, against the stored owner as well as the one the instance carries, and refuses a member whose policy changed after admission. A model the request did not resolve is held to the same rules under its live policy. Code that enters `withSystemContext()` inside a request acts as the system (and code that enters `withTenant()` in a request with no tenant acts in that tenant), except in a request admitted under a cross-tenant read grant, which writes no tenant-scoped row whatever context its code enters. This interceptor reads the bound policy for every member (`boundMemberTenancy`) instead of a fresh lookup, the member's `autoPopulate` included, and treats a bound member that is not `scoped` with a mode and field (a failed lookup) as an isolation error, never as unscoped.\n\n**`enableTenancy()` installs the policy source core decides with** (`setTenantPolicySource`): `policyOf(key)` is `getTenantScopedConfig()` by qualified key, reported as absent, resolved, or failed (an ambiguous or stale selector is `failed`, never \"not scoped\"; a failure always carries a reason), plus the system, bypass and hierarchy probes (`hierarchyReadScopeKey` keys read validators on the active hierarchy scope) and the context runners (a refreshed context keeps its other fields). For a principal the REST host resolves (#5195) it also lends `runForPrincipal(context | null, fn)` (`runInPrincipalContext`, internal: a frozen projection of the principal on this package's storage, its read-only permissions, never the bypass flag; `null` runs with no tenant and no system context) and `generation()`, a process-wide counter (`Symbol.for('smrt:tenant-policy-generation')`) bumped by every registration, removal, `clearTenantScopedRegistry()`, enable and disable. The request tenant context hooks (`setRequestTenantContextHooks`: enter, current, run, and the super-admin bypass, which answers only while tenancy is enabled) are installed when this package is loaded, enabled or not, so a route carrying a complete principal (`api.principalContext`) enters it for a model with no tenancy and an active context of another tenant refuses the request. `disableTenancy()` removes the policy source and keeps the context hooks. Enabled tenancy without a policy source refuses every scoped request. `runTenantScopedEntryPoint()` remains for direct callers; no generated surface uses it. Tests: `src/__tests__/effective-tenancy-*.test.ts`, `src/__tests__/rest-write-tenant-gate.test.ts`, `src/__tests__/rest-request-tenant.test.ts`.\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 (opted-in\n classes only) remain 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 of an\n opted-in class skip filtering but memory still keys to the active tenant\n (scoped tighter, not a 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 and lifts tenant enforcement (list/get filtering, raw-SQL policy, save/delete validation) **only for classes that opt in with `allowSuperAdminBypass: true`** (`@TenantScoped({ allowSuperAdminBypass: true })` or `@smrt({ tenantScoped: { allowSuperAdminBypass: true } })`). Every other tenant-scoped class — the flag defaults to `false` — stays scoped to the caller's tenant under bypass; unresolved config fails closed (#2973). Different from `withSystemContext()`, which removes context entirely and skips all checks. An active hierarchy read scope takes precedence: list/get remain bounded and tenant-scoped writes/raw queries reject.\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- **Runtime-only registration is audited, and ownership keys follow the field**: a class registered with `registerTenantScopedClass()` whose manifest declares no tenancy still gets the tenant-led default key when it has a `tenantId` field (core infers OWNERSHIP from the field, never the read policy). `auditTenantScopedRegistrations()` reports per selector: `missing_tenant_field` (error — neither the model nor a registered ancestor declares the field; an STI child registered before its manifest loads inherits it from the parent, #3623), `natural_key_not_tenant_scoped` (warning — an explicit key omits the tenant column, so a second tenant's same-key save is refused with `TENANT_ISOLATION_VIOLATION`), `undeclared_tenant_scope` (info). Registration (or first use, when it precedes core) logs the error/warning findings once. Core's save guard, not the interceptor, is what stops a tenant-filtered lookup from upserting onto another tenant's row (see 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\n## Portable model annotations (#4765)\n\nModel-only packages may import the original `TenantScoped`, `tenantId`, and\nannotation option types from `@happyvertical/smrt-tenancy/decorators`. This public\nentry reuses the same functions and registry as the root; it imports no context,\nAsyncLocalStorage, query helpers or adapters. It only declares metadata. Existing\nserver interception, context, filtering and RLS/authorization remain required and\nunchanged. Never replace these declarations with consumer-owned decorator stubs.\n",
154
154
  "browser": {
155
155
  "status": "server-only",
156
156
  "issues": [
@@ -5,10 +5,10 @@ description: "Production-ready multi-tenancy framework for SMRT with automatic t
5
5
  status: "stable"
6
6
  generated:
7
7
  by: "smrt/scripts/generate-knowledge-okf.ts"
8
- at: "2026-11-20T21:24:51Z"
8
+ at: "2026-11-22T06:38:20Z"
9
9
  audience: "internal"
10
10
  evidence_level: "source-inspected"
11
- source_revision: "sha256:331ecf8a80e77022d810394a86d2ca9ce42a744e25977e119c53b40044949547"
11
+ source_revision: "sha256:e2ebbc7f7229a3c65654b7ce438eab6aeb340c6105652149b64d9d413ea34837"
12
12
  sources:
13
13
  - id: "manifest"
14
14
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/tenancy/package.json"
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-BW08HnMy.js";
1
+ import { a as setupTestTenancy, i as resetTenancy, n as assertTenantIsolationViolation, o as testTenantIsolation, r as createTestTenantContext, t as assertTenantContextRequired } from "./chunks/testing-DCe_bmKi.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.69.0",
3
+ "version": "0.70.1",
4
4
  "smrtJsdoc": "strict",
5
5
  "description": "Production-ready multi-tenancy framework for SMRT with automatic tenant isolation and enforcement",
6
6
  "type": "module",
@@ -47,9 +47,9 @@
47
47
  },
48
48
  "dependencies": {
49
49
  "@happyvertical/logger": "^0.116.6",
50
- "@happyvertical/smrt-core": "0.69.0",
51
- "@happyvertical/smrt-types": "0.69.0",
52
- "@happyvertical/smrt-ui": "0.69.0",
50
+ "@happyvertical/smrt-core": "0.70.1",
51
+ "@happyvertical/smrt-types": "0.70.1",
52
+ "@happyvertical/smrt-ui": "0.70.1",
53
53
  "@happyvertical/sql": "^0.116.6",
54
54
  "@happyvertical/utils": "^0.116.6"
55
55
  },
@@ -62,7 +62,7 @@
62
62
  }
63
63
  },
64
64
  "devDependencies": {
65
- "@happyvertical/smrt-vitest": "0.69.0",
65
+ "@happyvertical/smrt-vitest": "0.70.1",
66
66
  "@sveltejs/package": "^2.5.8",
67
67
  "@sveltejs/vite-plugin-svelte": "^7.3.0",
68
68
  "@types/node": "24.13.6",
@@ -1 +0,0 @@
1
- {"version":3,"file":"registry-DH0v5Efm.js","names":[],"sources":["../../src/registry.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 { createLogger } from '@happyvertical/logger';\nimport { ObjectRegistry, toSnakeCase } from '@happyvertical/smrt-core';\n\nconst logger = createLogger({ level: 'info' });\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\n// Selectors already audited (and warned about) since their last registration.\nconst auditedSelectors = new Set<string>();\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 warnOnRegistrationMismatch(className);\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 auditedSelectors.delete(className);\n if (isQualifiedClassName(className)) {\n directQualifiedRegistrations.set(className, resolved);\n warnOnRegistrationMismatch(className);\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 warnOnRegistrationMismatch(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 auditedSelectors.delete(className);\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 const direct = getDeclaredTenantScopedConfig(className);\n const qualifiedName = ObjectRegistry.getClass(className)?.qualifiedName;\n if (\n direct &&\n qualifiedName &&\n ObjectRegistry.getRuntimeOverride(qualifiedName)?.tenancy\n ) {\n return { ...direct, mode: 'required' };\n }\n return direct;\n}\n\nfunction getDeclaredTenantScopedConfig(\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 // A qualified selector registered before core learned the class is\n // audited on first use instead.\n if (!auditedSelectors.has(className)) warnOnRegistrationMismatch(className);\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) return direct;\n // Otherwise inherit recognition from a tenant-scoped STI ancestor (#1596).\n return getInheritedTenantScopedConfig(className);\n}\n\n/**\n * Tell core which column records a row's owner for every tenant-scoped class,\n * including runtime registrations on a custom field\n * (`registerTenantScopedClass('Team', { field: 'organizationId' })`) that the\n * manifest knows nothing about. Core's natural-key save guard compares these\n * columns, so a save whose key collides with another organization's row is\n * refused (`TENANT_ISOLATION_VIOLATION`) instead of adopting it. Resolved on\n * every lookup, so selectors that bind later or are unregistered are honoured.\n */\nObjectRegistry.registerOwnershipColumnSource((qualifiedName) => {\n const config = getTenantScopedConfig(qualifiedName);\n return config ? [toSnakeCase(config.field)] : undefined;\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 auditedSelectors.clear();\n tenantScopedClasses.clear();\n directSimpleRegistrations.clear();\n directQualifiedRegistrations.clear();\n directSimpleBindings.clear();\n unregisteredDecoratorRegistrations.clear();\n}\n\n/**\n * One finding from {@link auditTenantScopedRegistrations}.\n *\n * - `missing_tenant_field` (`error`): the class has no field named by the\n * registration, so the interceptor filters and populates a column that does\n * not exist in the model's manifest/schema.\n * - `natural_key_not_tenant_scoped` (`warning`): the class's upsert conflict\n * target (and so its unique index) omits the tenant column — its natural key\n * is unique ACROSS tenants. The interceptor hides other tenants' rows from\n * lookups, so a second tenant's same-key save collides with a row it cannot\n * see; core refuses that save (`TENANT_ISOLATION_VIOLATION`) instead of\n * overwriting the other tenant's row, but the second tenant still cannot\n * store the key.\n * - `undeclared_tenant_scope` (`info`): tenant scope exists only as this\n * runtime registration; the model's manifest declares no tenancy. Its\n * default natural key is still tenant-led when it has a `tenantId` field,\n * but generated surfaces, knowledge, and schema contracts cannot see the\n * read policy. Declaring `@smrt({ tenantScoped })` makes it visible.\n */\nexport interface TenantRegistrationFinding {\n /** The selector passed to `registerTenantScopedClass()`. */\n selector: string;\n /** The core class it resolved to (qualified name when known). */\n className: string;\n kind:\n | 'missing_tenant_field'\n | 'natural_key_not_tenant_scoped'\n | 'undeclared_tenant_scope';\n severity: 'error' | 'warning' | 'info';\n message: string;\n}\n\nfunction resolveSelectorClass(selector: string) {\n if (isQualifiedClassName(selector)) {\n return ObjectRegistry.getClassByQualifiedName(selector);\n }\n const bound = directSimpleBindings.get(selector);\n if (bound) return ObjectRegistry.getClassByQualifiedName(bound.qualifiedName);\n const matches = ObjectRegistry.findClassesByName(selector);\n return matches.length === 1 ? matches[0] : undefined;\n}\n\ntype RegisteredSmrtClass = NonNullable<ReturnType<typeof resolveSelectorClass>>;\n\n/**\n * Whether the class or one of its registered ancestors declares `fieldName`.\n *\n * A class's own field map holds only its own decorator fields until its\n * manifest entry loads; an STI child registered first (a bundled server) has\n * its inherited tenant field on the registered parent only (#3623). Walk the\n * constructor's prototype chain through public registry lookups — read-only,\n * unlike `getInheritanceChain()`, which caches whatever partial chain exists\n * at registration time.\n */\nfunction declaresFieldInChain(\n registered: RegisteredSmrtClass,\n fieldName: string,\n): boolean {\n if (registered.fields.has(fieldName)) return true;\n if (registered.inheritedFields?.has(fieldName)) return true;\n const visited = new Set<unknown>([registered.constructor]);\n let ctor: unknown = Object.getPrototypeOf(registered.constructor);\n while (typeof ctor === 'function' && !visited.has(ctor)) {\n visited.add(ctor);\n const ancestor = ObjectRegistry.getClassByConstructor(\n ctor as RegisteredSmrtClass['constructor'],\n );\n if (ancestor?.fields.has(fieldName)) return true;\n ctor = Object.getPrototypeOf(ctor);\n }\n return false;\n}\n\nfunction auditSelector(\n selector: string,\n config: TenantScopedConfig,\n): TenantRegistrationFinding[] {\n const registered = resolveSelectorClass(selector);\n if (!registered) return [];\n const className = registered.qualifiedName || registered.name;\n const findings: TenantRegistrationFinding[] = [];\n\n if (!declaresFieldInChain(registered, config.field)) {\n findings.push({\n selector,\n className,\n kind: 'missing_tenant_field',\n severity: 'error',\n message:\n `${className} is registered tenant-scoped on field '${config.field}', ` +\n 'but the model declares no such field. Tenant filtering and population ' +\n 'target a column its manifest and schema do not have. Add the field ' +\n '(or declare `@smrt({ tenantScoped })`) and regenerate the manifest.',\n });\n return findings;\n }\n\n if (!ObjectRegistry.getTenantScopedConfig(className)) {\n findings.push({\n selector,\n className,\n kind: 'undeclared_tenant_scope',\n severity: 'info',\n message:\n `${className} is tenant-scoped only by runtime registration; its ` +\n 'manifest declares no tenancy. Declare `@smrt({ tenantScoped })` so ' +\n 'schema, generated surfaces and knowledge agree with the read policy.',\n });\n }\n\n const tenantColumn = toSnakeCase(config.field);\n const conflictColumns = ObjectRegistry.getConflictColumns(className);\n const keyedOnPrimaryKey =\n conflictColumns.length === 1 && conflictColumns[0] === 'id';\n if (!keyedOnPrimaryKey && !conflictColumns.includes(tenantColumn)) {\n findings.push({\n selector,\n className,\n kind: 'natural_key_not_tenant_scoped',\n severity: 'warning',\n message:\n `${className} is registered tenant-scoped, but its natural key ` +\n `(${conflictColumns.join(', ')}) omits '${tenantColumn}', so it is ` +\n 'unique across tenants: a second tenant cannot store a key another ' +\n 'tenant already uses. A new object saved on such a key is refused ' +\n '(TENANT_ISOLATION_VIOLATION) when the row it collides with has a ' +\n `different '${tenantColumn}'; one whose slug was derived from its ` +\n 'name moves to a free slug instead. ' +\n `Include '${tenantColumn}' in the conflict columns (or drop the ` +\n 'explicit conflictColumns) and run `smrt db:migrate`.',\n });\n }\n return findings;\n}\n\n/**\n * Audit every string-selector registration (`registerTenantScopedClass()`)\n * against the core model it resolves to. Selectors whose class core has not\n * registered yet are skipped (they are audited when they bind).\n *\n * Registration also runs this per selector and logs `error`/`warning`\n * findings once, so a mismatch surfaces at startup; call this directly for a\n * complete report (for example from a health check or a test).\n */\nexport function auditTenantScopedRegistrations(): TenantRegistrationFinding[] {\n const findings: TenantRegistrationFinding[] = [];\n for (const [selector, config] of directQualifiedRegistrations) {\n findings.push(...auditSelector(selector, config));\n }\n for (const [selector, config] of directSimpleRegistrations) {\n findings.push(...auditSelector(selector, config));\n }\n return findings;\n}\n\nfunction warnOnRegistrationMismatch(selector: string): void {\n if (auditedSelectors.has(selector)) return;\n const config =\n directQualifiedRegistrations.get(selector) ??\n directSimpleRegistrations.get(selector);\n if (!config) return;\n let findings: TenantRegistrationFinding[];\n try {\n findings = auditSelector(selector, config);\n } catch {\n // Ambiguous or stale identities fail closed on use; the audit stays quiet.\n return;\n }\n if (!resolveSelectorClass(selector)) return; // not in core yet; retry later\n auditedSelectors.add(selector);\n for (const finding of findings) {\n if (finding.severity === 'info') continue;\n logger.warn(`[smrt-tenancy] ${finding.message}`);\n }\n}\n"],"mappings":";;;AAmBA,IAAM,SAAS,aAAa,EAAE,OAAO,OAAO,CAAC;AA6C7C,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;AAGF,IAAM,mCAAmB,IAAI,IAAY;AAEzC,SAAS,qBAAqB,WAA4B;CACxD,OAAO,UAAU,SAAS,GAAG;AAC/B;AAEA,SAAS,6BAA6B,SAG1B;CACV,OACE,eAAe,wBAAwB,QA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