@pattern-stack/codegen 0.7.8 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +54 -0
- package/dist/runtime/base-classes/activity-entity-repository.js +98 -17
- package/dist/runtime/base-classes/activity-entity-repository.js.map +1 -1
- package/dist/runtime/base-classes/base-repository.d.ts +47 -3
- package/dist/runtime/base-classes/base-repository.js +98 -17
- package/dist/runtime/base-classes/base-repository.js.map +1 -1
- package/dist/runtime/base-classes/index.d.ts +1 -0
- package/dist/runtime/base-classes/index.js +137 -28
- package/dist/runtime/base-classes/index.js.map +1 -1
- package/dist/runtime/base-classes/junction-sync-repository.js +102 -21
- package/dist/runtime/base-classes/junction-sync-repository.js.map +1 -1
- package/dist/runtime/base-classes/knowledge-entity-repository.js +98 -17
- package/dist/runtime/base-classes/knowledge-entity-repository.js.map +1 -1
- package/dist/runtime/base-classes/metadata-entity-repository.js +101 -20
- package/dist/runtime/base-classes/metadata-entity-repository.js.map +1 -1
- package/dist/runtime/base-classes/synced-entity-repository.js +103 -22
- package/dist/runtime/base-classes/synced-entity-repository.js.map +1 -1
- package/dist/runtime/base-classes/tenant-context.d.ts +79 -0
- package/dist/runtime/base-classes/tenant-context.js +46 -0
- package/dist/runtime/base-classes/tenant-context.js.map +1 -0
- package/dist/src/cli/index.js +2 -0
- package/dist/src/cli/index.js.map +1 -1
- package/package.json +1 -1
- package/runtime/base-classes/base-repository.ts +96 -20
- package/runtime/base-classes/index.ts +13 -0
- package/runtime/base-classes/tenant-context.ts +175 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../runtime/base-classes/base-repository.ts"],"sourcesContent":["/**\n * BaseRepository<TEntity>\n *\n * Abstract base class providing standard CRUD operations via Drizzle ORM.\n * Every generated repository extends this class.\n *\n * Family-specific bases (CrmEntityRepository, etc.) extend this in v0.1\n * without any changes to BaseRepository.\n *\n * NOT @Injectable — concrete repositories are @Injectable and inject DRIZZLE.\n */\nimport { eq, inArray, isNull, sql } from 'drizzle-orm';\nimport type { PgTableWithColumns, PgColumn } from 'drizzle-orm/pg-core';\nimport type { SQL } from 'drizzle-orm';\nimport type { DrizzleClient, DrizzleTx } from '../types/drizzle';\n\n// ============================================================================\n// Interfaces\n// ============================================================================\n\n/**\n * Behavior flags for the repository. Controls automatic timestamp injection\n * and soft-delete filtering.\n */\nexport interface BehaviorConfig {\n timestamps: boolean;\n softDelete: boolean;\n userTracking: boolean;\n}\n\n/**\n * Options for the list() method.\n */\nexport interface ListOptions {\n where?: SQL;\n limit?: number;\n offset?: number;\n orderBy?: PgColumn | SQL;\n}\n\n// ============================================================================\n// BaseRepository\n// ============================================================================\n\nexport abstract class BaseRepository<TEntity> {\n /**\n * The Drizzle table schema for this entity.\n * Concrete repositories declare this as a class property.\n */\n protected abstract readonly table: PgTableWithColumns<any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n\n /**\n * Behavior flags controlling automatic behavior injection.\n * Override in concrete repositories to enable behaviors.\n */\n protected readonly behaviors: BehaviorConfig = {\n timestamps: false,\n softDelete: false,\n userTracking: false,\n };\n\n protected readonly db: DrizzleClient;\n\n constructor(db: DrizzleClient) {\n this.db = db;\n }\n\n /**\n * Pick the runner for a write: the caller-supplied transaction handle\n * if present, otherwise the repository's own client. Keeps the `tx`\n * parameter purely additive — callers without a transaction call as\n * before. Used by the write methods below + consumer overrides (e.g.\n * the generated `upsertCurrentValues` on EAV value tables).\n */\n protected runner(tx?: DrizzleTx): DrizzleClient {\n return tx ?? this.db;\n }\n\n // ============================================================================\n // Read Operations\n // ============================================================================\n\n /**\n * Find a single entity by its primary key.\n * Returns null if not found (or soft-deleted when softDelete=true).\n */\n async findById(id: string): Promise<TEntity | null> {\n const rows = await this.baseQuery()\n .where(eq(this.table['id'], id))\n .limit(1);\n return (rows[0] as TEntity) ?? null;\n }\n\n /**\n * Find multiple entities by their primary keys.\n * Returns empty array immediately for empty input (avoids DB errors).\n */\n async findByIds(ids: string[]): Promise<TEntity[]> {\n if (ids.length === 0) return [];\n const rows = await this.baseQuery().where(inArray(this.table['id'], ids));\n return rows as TEntity[];\n }\n\n /**\n * List entities with optional filtering, pagination, and ordering.\n */\n async list(options?: ListOptions): Promise<TEntity[]> {\n let query = this.baseQuery();\n\n if (options?.where) {\n query = query.where(options.where) as typeof query;\n }\n if (options?.orderBy) {\n query = query.orderBy(options.orderBy as SQL) as typeof query;\n }\n if (options?.limit !== undefined) {\n query = query.limit(options.limit) as typeof query;\n }\n if (options?.offset !== undefined) {\n query = query.offset(options.offset) as typeof query;\n }\n\n const rows = await query;\n return rows as TEntity[];\n }\n\n /**\n * Count entities matching an optional WHERE clause.\n * Soft-deleted rows are always excluded when softDelete=true.\n */\n async count(where?: SQL): Promise<number> {\n let query = this.db\n .select({ count: sql<number>`cast(count(*) as integer)` })\n .from(this.table);\n\n const conditions: SQL[] = [];\n if (this.behaviors.softDelete) {\n conditions.push(isNull(this.table['deletedAt']));\n }\n if (where) {\n conditions.push(where);\n }\n\n if (conditions.length === 1) {\n query = query.where(conditions[0]) as typeof query;\n } else if (conditions.length > 1) {\n // Combine with AND by building the condition inline\n const { and } = await import('drizzle-orm');\n query = query.where(and(...conditions)) as typeof query;\n }\n\n const rows = await query;\n return rows[0]?.count ?? 0;\n }\n\n /**\n * Check whether an entity with the given id exists.\n */\n async exists(id: string): Promise<boolean> {\n const result = await this.findById(id);\n return result !== null;\n }\n\n // ============================================================================\n // Write Operations\n // ============================================================================\n\n /**\n * Insert a new entity. Timestamps are auto-injected when timestamps=true.\n */\n async create(input: Partial<TEntity>, tx?: DrizzleTx): Promise<TEntity> {\n const data = this.withTimestamps(input as Record<string, unknown>, 'create');\n const rows = await this.runner(tx)\n .insert(this.table)\n .values(data as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .returning();\n return rows[0] as TEntity;\n }\n\n /**\n * Update an existing entity by id. updatedAt is auto-injected when timestamps=true.\n * Returns the updated entity.\n */\n async update(id: string, input: Partial<TEntity>, tx?: DrizzleTx): Promise<TEntity> {\n const data = this.withTimestamps(input as Record<string, unknown>, 'update');\n const rows = await this.runner(tx)\n .update(this.table)\n .set(data as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .where(eq(this.table['id'], id))\n .returning();\n return rows[0] as TEntity;\n }\n\n /**\n * Delete an entity by id.\n * - softDelete=true: sets deletedAt to current timestamp\n * - softDelete=false: hard-deletes the row\n */\n async delete(id: string, tx?: DrizzleTx): Promise<void> {\n const runner = this.runner(tx);\n if (this.behaviors.softDelete) {\n await runner\n .update(this.table)\n .set({ deletedAt: new Date() } as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .where(eq(this.table['id'], id));\n } else {\n await runner\n .delete(this.table)\n .where(eq(this.table['id'], id));\n }\n }\n\n /**\n * Insert or update multiple entities.\n * Default naive implementation — family repositories override with\n * proper conflict-target upsert (e.g., CrmEntityRepository).\n */\n async upsertMany(inputs: Array<Partial<TEntity>>, tx?: DrizzleTx): Promise<TEntity[]> {\n return Promise.all(inputs.map((input) => this.create(input, tx)));\n }\n\n // ============================================================================\n // Protected Helpers\n // ============================================================================\n\n /**\n * Base SELECT query that automatically excludes soft-deleted rows\n * when softDelete behavior is enabled.\n */\n protected baseQuery() {\n const query = this.db.select().from(this.table).$dynamic();\n if (this.behaviors.softDelete) {\n return query.where(isNull(this.table['deletedAt']));\n }\n return query;\n }\n\n /**\n * Merge timestamp fields into an input object.\n * - mode='create': adds createdAt and updatedAt\n * - mode='update': adds updatedAt only\n *\n * No-op when timestamps behavior is disabled.\n */\n protected withTimestamps(\n input: Record<string, unknown>,\n mode: 'create' | 'update',\n ): Record<string, unknown> {\n if (!this.behaviors.timestamps) return input;\n const now = new Date();\n if (mode === 'create') {\n return { ...input, createdAt: now, updatedAt: now };\n }\n return { ...input, updatedAt: now };\n }\n\n /**\n * Build a WHERE clause fragment that restricts results to rows whose\n * parent (identified by a belongs_to FK) is not soft-deleted.\n *\n * Use this in custom repository methods when you need \"rows reachable\n * from an active parent\". The default findAll / findById behavior is\n * NOT changed by this helper — opt in explicitly where needed.\n *\n * ADR-021 — Soft-delete cascade: Option A (filter at query time).\n * `on_delete` FK rules do not fire for soft-deletes; use this helper\n * instead of expecting cascade semantics on the DB level.\n *\n * Example:\n * async listActiveMessages(): Promise<Message[]> {\n * return this.list({\n * where: this.activeParentFilter(conversations, this.table['conversationId']),\n * });\n * }\n *\n * @param parentTable The Drizzle table object for the parent entity.\n * @param parentFkColumn The FK column on this (child) table that references parent.id.\n */\n protected activeParentFilter(\n parentTable: PgTableWithColumns<any>, // eslint-disable-line @typescript-eslint/no-explicit-any\n parentFkColumn: PgColumn,\n ): SQL {\n return sql`EXISTS (\n SELECT 1 FROM ${parentTable} p\n WHERE p.id = ${parentFkColumn}\n AND p.deleted_at IS NULL\n )`;\n }\n}\n"],"mappings":";AAWA,SAAS,IAAI,SAAS,QAAQ,WAAW;AAiClC,IAAe,iBAAf,MAAuC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWzB,YAA4B;AAAA,IAC7C,YAAY;AAAA,IACZ,YAAY;AAAA,IACZ,cAAc;AAAA,EAChB;AAAA,EAEmB;AAAA,EAEnB,YAAY,IAAmB;AAC7B,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASU,OAAO,IAA+B;AAC9C,WAAO,MAAM,KAAK;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,SAAS,IAAqC;AAClD,UAAM,OAAO,MAAM,KAAK,UAAU,EAC/B,MAAM,GAAG,KAAK,MAAM,IAAI,GAAG,EAAE,CAAC,EAC9B,MAAM,CAAC;AACV,WAAQ,KAAK,CAAC,KAAiB;AAAA,EACjC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,UAAU,KAAmC;AACjD,QAAI,IAAI,WAAW,EAAG,QAAO,CAAC;AAC9B,UAAM,OAAO,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QAAQ,KAAK,GAAG,OAAO,EAAE,KAAK,KAAK,KAAK,EAAE,SAAS;AACzD,QAAI,KAAK,UAAU,YAAY;AAC7B,aAAO,MAAM,MAAM,OAAO,KAAK,MAAM,WAAW,CAAC,CAAC;AAAA,IACpD;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASU,eACR,OACA,MACyB;AACzB,QAAI,CAAC,KAAK,UAAU,WAAY,QAAO;AACvC,UAAM,MAAM,oBAAI,KAAK;AACrB,QAAI,SAAS,UAAU;AACrB,aAAO,EAAE,GAAG,OAAO,WAAW,KAAK,WAAW,IAAI;AAAA,IACpD;AACA,WAAO,EAAE,GAAG,OAAO,WAAW,IAAI;AAAA,EACpC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAwBU,mBACR,aACA,gBACK;AACL,WAAO;AAAA,sBACW,WAAW;AAAA,qBACZ,cAAc;AAAA;AAAA;AAAA,EAGjC;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../runtime/base-classes/base-repository.ts","../../../runtime/base-classes/tenant-context.ts"],"sourcesContent":["/**\n * BaseRepository<TEntity>\n *\n * Abstract base class providing standard CRUD operations via Drizzle ORM.\n * Every generated repository extends this class.\n *\n * Family-specific bases (CrmEntityRepository, etc.) extend this in v0.1\n * without any changes to BaseRepository.\n *\n * NOT @Injectable — concrete repositories are @Injectable and inject DRIZZLE.\n */\nimport { and, eq, inArray, isNull, sql } from 'drizzle-orm';\nimport type { PgTableWithColumns, PgColumn } from 'drizzle-orm/pg-core';\nimport type { SQL } from 'drizzle-orm';\nimport type { DrizzleClient, DrizzleTx } from '../types/drizzle';\nimport {\n requireRequester,\n tryGetRequester,\n type RequesterScope,\n} from './tenant-context';\n\n// ============================================================================\n// Interfaces\n// ============================================================================\n\n/**\n * Behavior flags for the repository. Controls automatic timestamp injection\n * and soft-delete filtering.\n */\nexport interface BehaviorConfig {\n timestamps: boolean;\n softDelete: boolean;\n userTracking: boolean;\n}\n\n/**\n * Options for the list() method.\n */\nexport interface ListOptions {\n where?: SQL;\n limit?: number;\n offset?: number;\n orderBy?: PgColumn | SQL;\n}\n\n// ============================================================================\n// BaseRepository\n// ============================================================================\n\nexport abstract class BaseRepository<TEntity> {\n /**\n * The Drizzle table schema for this entity.\n * Concrete repositories declare this as a class property.\n */\n protected abstract readonly table: PgTableWithColumns<any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n\n /**\n * Behavior flags controlling automatic behavior injection.\n * Override in concrete repositories to enable behaviors.\n */\n protected readonly behaviors: BehaviorConfig = {\n timestamps: false,\n softDelete: false,\n userTracking: false,\n };\n\n /**\n * Ambient tenant-scope enforcement for `userTracking` repos (see\n * `scopePredicate`). Only has effect when `behaviors.userTracking === true`.\n *\n * - `'lenient'` (default): when no ambient requester context is active,\n * reads/writes are NOT scoped — preserves pre-scoping behavior, so adopting\n * ambient scoping is additive. Scoping kicks in automatically once a\n * boundary installs `withRequester(...)`.\n * - `'strict'`: a missing ambient context throws (`requireRequester`),\n * making a forgotten boundary fail loud instead of silently returning\n * cross-tenant rows. Recommended for new multi-tenant consumers — override\n * in a concrete repo or a family base class.\n */\n protected readonly scopeEnforcement: 'lenient' | 'strict' = 'lenient';\n\n protected readonly db: DrizzleClient;\n\n constructor(db: DrizzleClient) {\n this.db = db;\n }\n\n /**\n * Pick the runner for a write: the caller-supplied transaction handle\n * if present, otherwise the repository's own client. Keeps the `tx`\n * parameter purely additive — callers without a transaction call as\n * before. Used by the write methods below + consumer overrides (e.g.\n * the generated `upsertCurrentValues` on EAV value tables).\n */\n protected runner(tx?: DrizzleTx): DrizzleClient {\n return tx ?? this.db;\n }\n\n // ============================================================================\n // Read Operations\n // ============================================================================\n\n /**\n * Find a single entity by its primary key.\n * Returns null if not found (or soft-deleted when softDelete=true).\n */\n async findById(id: string): Promise<TEntity | null> {\n const rows = await this.baseQuery(eq(this.table['id'], id)).limit(1);\n return (rows[0] as TEntity) ?? null;\n }\n\n /**\n * Find multiple entities by their primary keys.\n * Returns empty array immediately for empty input (avoids DB errors).\n */\n async findByIds(ids: string[]): Promise<TEntity[]> {\n if (ids.length === 0) return [];\n const rows = await this.baseQuery(inArray(this.table['id'], ids));\n return rows as TEntity[];\n }\n\n /**\n * List entities with optional filtering, pagination, and ordering.\n */\n async list(options?: ListOptions): Promise<TEntity[]> {\n let query = this.baseQuery(options?.where);\n\n if (options?.orderBy) {\n query = query.orderBy(options.orderBy as SQL) as typeof query;\n }\n if (options?.limit !== undefined) {\n query = query.limit(options.limit) as typeof query;\n }\n if (options?.offset !== undefined) {\n query = query.offset(options.offset) as typeof query;\n }\n\n const rows = await query;\n return rows as TEntity[];\n }\n\n /**\n * Count entities matching an optional WHERE clause.\n * Soft-deleted rows are always excluded when softDelete=true.\n */\n async count(where?: SQL): Promise<number> {\n let query = this.db\n .select({ count: sql<number>`cast(count(*) as integer)` })\n .from(this.table);\n\n const conditions: SQL[] = [];\n if (this.behaviors.softDelete) {\n conditions.push(isNull(this.table['deletedAt']));\n }\n const scope = this.scopePredicate();\n if (scope) {\n conditions.push(scope);\n }\n if (where) {\n conditions.push(where);\n }\n\n if (conditions.length === 1) {\n query = query.where(conditions[0]) as typeof query;\n } else if (conditions.length > 1) {\n query = query.where(and(...conditions)) as typeof query;\n }\n\n const rows = await query;\n return rows[0]?.count ?? 0;\n }\n\n /**\n * Check whether an entity with the given id exists.\n */\n async exists(id: string): Promise<boolean> {\n const result = await this.findById(id);\n return result !== null;\n }\n\n // ============================================================================\n // Write Operations\n // ============================================================================\n\n /**\n * Insert a new entity. Timestamps are auto-injected when timestamps=true.\n */\n async create(input: Partial<TEntity>, tx?: DrizzleTx): Promise<TEntity> {\n const data = this.withTimestamps(input as Record<string, unknown>, 'create');\n const rows = await this.runner(tx)\n .insert(this.table)\n .values(data as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .returning();\n return rows[0] as TEntity;\n }\n\n /**\n * Update an existing entity by id. updatedAt is auto-injected when timestamps=true.\n * Returns the updated entity.\n */\n async update(id: string, input: Partial<TEntity>, tx?: DrizzleTx): Promise<TEntity> {\n const data = this.withTimestamps(input as Record<string, unknown>, 'update');\n const rows = await this.runner(tx)\n .update(this.table)\n .set(data as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .where(this.scopeAnd(eq(this.table['id'], id)))\n .returning();\n return rows[0] as TEntity;\n }\n\n /**\n * Delete an entity by id.\n * - softDelete=true: sets deletedAt to current timestamp\n * - softDelete=false: hard-deletes the row\n */\n async delete(id: string, tx?: DrizzleTx): Promise<void> {\n const runner = this.runner(tx);\n if (this.behaviors.softDelete) {\n await runner\n .update(this.table)\n .set({ deletedAt: new Date() } as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .where(this.scopeAnd(eq(this.table['id'], id)));\n } else {\n await runner\n .delete(this.table)\n .where(this.scopeAnd(eq(this.table['id'], id)));\n }\n }\n\n /**\n * Insert or update multiple entities.\n * Default naive implementation — family repositories override with\n * proper conflict-target upsert (e.g., CrmEntityRepository).\n */\n async upsertMany(inputs: Array<Partial<TEntity>>, tx?: DrizzleTx): Promise<TEntity[]> {\n return Promise.all(inputs.map((input) => this.create(input, tx)));\n }\n\n // ============================================================================\n // Protected Helpers\n // ============================================================================\n\n /**\n * Base SELECT query that automatically applies the ambient guards —\n * soft-delete exclusion (when `softDelete`) and tenant scope (when\n * `userTracking` + an active requester context) — combined with an optional\n * caller `extra` predicate into a SINGLE `WHERE`.\n *\n * Pass the leaf predicate as `extra` rather than chaining a second\n * `.where(...)`: Drizzle's `.where()` OVERRIDES (does not AND) a prior\n * `.where()` on a `$dynamic()` query, so a chained call would silently drop\n * the soft-delete and scope guards. `baseQuery(extra)` is the safe form.\n */\n protected baseQuery(extra?: SQL) {\n const query = this.db.select().from(this.table).$dynamic();\n const where = this.scopeAnd(extra, { softDelete: this.behaviors.softDelete });\n return where ? query.where(where) : query;\n }\n\n /**\n * Build the ambient tenant-scope predicate for this repo's table.\n *\n * Returns `undefined` (no scoping) when:\n * - `behaviors.userTracking` is false (repo is not user-owned), or\n * - no ambient requester context is active AND `scopeEnforcement` is\n * `'lenient'` (the default — preserves pre-scoping behavior).\n *\n * When a requester context is active, scopes by `user_id` per the ambient\n * scope: `'user'` → `user_id = ctx.userId`; `'org'` → `user_id IN\n * ctx.orgUserIds` (empty list matches nothing — fail-closed); `'superuser'`\n * → no filter. See `tenant-context.ts` for the boundary-install contract.\n */\n protected scopePredicate(): SQL | undefined {\n if (!this.behaviors.userTracking) return undefined;\n const ctx =\n this.scopeEnforcement === 'strict'\n ? requireRequester()\n : tryGetRequester();\n if (!ctx) return undefined;\n const scope: RequesterScope = ctx.scope ?? 'user';\n switch (scope) {\n case 'superuser':\n return undefined;\n case 'org':\n return ctx.orgUserIds && ctx.orgUserIds.length > 0\n ? inArray(this.table['userId'], ctx.orgUserIds as string[])\n : sql`false`;\n case 'user':\n default:\n return eq(this.table['userId'], ctx.userId);\n }\n }\n\n /**\n * Combine the ambient scope predicate (and, optionally, the soft-delete\n * guard) with a caller `extra` predicate into one `SQL`. Returns `undefined`\n * when nothing applies. Used by read + by-id write paths so a single\n * `.where(...)` carries every guard.\n */\n protected scopeAnd(\n extra?: SQL,\n opts?: { softDelete?: boolean },\n ): SQL | undefined {\n const conditions: SQL[] = [];\n if (opts?.softDelete) conditions.push(isNull(this.table['deletedAt']));\n const scope = this.scopePredicate();\n if (scope) conditions.push(scope);\n if (extra) conditions.push(extra);\n if (conditions.length === 0) return undefined;\n if (conditions.length === 1) return conditions[0];\n return and(...conditions);\n }\n\n /**\n * Merge timestamp fields into an input object.\n * - mode='create': adds createdAt and updatedAt\n * - mode='update': adds updatedAt only\n *\n * No-op when timestamps behavior is disabled.\n */\n protected withTimestamps(\n input: Record<string, unknown>,\n mode: 'create' | 'update',\n ): Record<string, unknown> {\n if (!this.behaviors.timestamps) return input;\n const now = new Date();\n if (mode === 'create') {\n return { ...input, createdAt: now, updatedAt: now };\n }\n return { ...input, updatedAt: now };\n }\n\n /**\n * Build a WHERE clause fragment that restricts results to rows whose\n * parent (identified by a belongs_to FK) is not soft-deleted.\n *\n * Use this in custom repository methods when you need \"rows reachable\n * from an active parent\". The default findAll / findById behavior is\n * NOT changed by this helper — opt in explicitly where needed.\n *\n * ADR-021 — Soft-delete cascade: Option A (filter at query time).\n * `on_delete` FK rules do not fire for soft-deletes; use this helper\n * instead of expecting cascade semantics on the DB level.\n *\n * Example:\n * async listActiveMessages(): Promise<Message[]> {\n * return this.list({\n * where: this.activeParentFilter(conversations, this.table['conversationId']),\n * });\n * }\n *\n * @param parentTable The Drizzle table object for the parent entity.\n * @param parentFkColumn The FK column on this (child) table that references parent.id.\n */\n protected activeParentFilter(\n parentTable: PgTableWithColumns<any>, // eslint-disable-line @typescript-eslint/no-explicit-any\n parentFkColumn: PgColumn,\n ): SQL {\n return sql`EXISTS (\n SELECT 1 FROM ${parentTable} p\n WHERE p.id = ${parentFkColumn}\n AND p.deleted_at IS NULL\n )`;\n }\n}\n","/**\n * Ambient requester context — AsyncLocalStorage-backed tenant scope.\n *\n * The alternative to threading `userId`/`organizationId` through every\n * repository/service signature. Set ONCE at each boundary the generated app\n * owns, read implicitly inside `BaseRepository` (see `scopePredicate`).\n *\n * ## Where to set it (boundaries)\n *\n * - HTTP / tRPC handlers — from the authenticated `ctx.user`\n * - OAuth callback controllers — from the authenticated session\n * - Queue/worker `process()` — from the job's owning user after the\n * job's record is loaded\n *\n * Each boundary wraps the rest of the request in `withRequester({ userId,\n * organizationId }, () => ...)`. The context propagates through every `await`\n * to all downstream repo/service calls without being passed explicitly.\n *\n * ## Where to read it\n *\n * - `BaseRepository.scopePredicate()` reads it (via `tryGetRequester` in\n * lenient mode, `requireRequester` in strict mode) and filters every read\n * by the ambient scope when the repo declares `userTracking: true`.\n *\n * ## Why AsyncLocalStorage over an explicit parameter\n *\n * Threading `userId` (and later `organizationId`) through dozens of method\n * signatures is pure parameter pollution. Ambient context also lets a repo\n * make the \"I forgot to scope\" mistake impossible at runtime: in strict mode\n * `requireRequester()` throws when no context is active, surfacing a missing\n * boundary call loudly rather than silently leaking cross-tenant data.\n *\n * ## Not-found semantics\n *\n * When a row exists but belongs to a different requester, scoped reads return\n * `null`/`[]` — identical to \"truly doesn't exist\". No existence oracle;\n * callers throw NotFound uniformly. Standard security practice.\n *\n * ## Testing\n *\n * Tests that exercise scoped repos must wrap the call in `withRequester(...)`.\n * In strict mode an unwrapped call hitting `requireRequester()` throws — by\n * design. In lenient mode (the default) an unwrapped call is simply unscoped.\n */\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/**\n * Data-visibility scope. The auth layer decides which scope a request is\n * allowed to claim; the repo trusts whatever the ambient context says.\n *\n * - `'user'`: filter every read by `user_id = ctx.userId`. Default.\n * - `'org'`: filter every read by membership in the requester's org, resolved\n * via `user_id IN (ctx.orgUserIds)` rather than via a per-entity\n * `organization_id` column. Works for every user-owned table and keeps repos\n * single-table — the org member list is pre-resolved at the boundary.\n * - `'superuser'`: no scope filter. Engineering / internal-tools only.\n *\n * AUTHORIZATION (who is allowed to claim each scope) lives in boundary\n * middleware, not in the repo. The repo trusts the ambient context — same\n * trust model as a threaded `userId`.\n */\nexport type RequesterScope = 'user' | 'org' | 'superuser';\n\nexport interface RequesterContext {\n /**\n * The user making the request. Always present — even in `'org'` and\n * `'superuser'` scopes it is the audit-trail \"who actually did this\".\n */\n readonly userId: string;\n /**\n * The organization the requester belongs to. Required when\n * `scope === 'org'`; may be null for `'user'` (users with no org) and for\n * `'superuser'` (cross-org reads).\n */\n readonly organizationId: string | null;\n /**\n * Data-visibility scope. Defaults to `'user'` when omitted.\n */\n readonly scope?: RequesterScope;\n /**\n * For `scope === 'org'`: the list of user IDs in the requester's org,\n * pre-resolved by the boundary middleware that established the `'org'`\n * scope (one `SELECT users.id WHERE organization_id = X` at the trust\n * boundary). Repos use this as a literal `IN (...)` filter — they never\n * JOIN to `users` themselves. Required when `scope === 'org'`.\n */\n readonly orgUserIds?: readonly string[];\n}\n\nconst als = new AsyncLocalStorage<RequesterContext>();\n\n/**\n * Set the ambient requester context for the duration of `fn`. The context\n * propagates through `await` boundaries to all downstream calls. Nesting is\n * fine — an inner `withRequester` overrides the outer for its callback.\n */\nexport function withRequester<T>(\n ctx: RequesterContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return als.run(ctx, fn);\n}\n\n/**\n * Read the ambient requester context. Throws if no context is active — by\n * design. Used by repos in strict scope-enforcement mode; an unwrapped call\n * site is a missing boundary.\n */\nexport function requireRequester(): RequesterContext {\n const ctx = als.getStore();\n if (!ctx) {\n throw new Error(\n 'No requester context active. Wrap the entry point in ' +\n 'withRequester({ userId, organizationId }, fn). See tenant-context.ts.',\n );\n }\n return ctx;\n}\n\n/**\n * Read the ambient requester context without throwing. Returns `undefined`\n * when no context is active. Used by repos in lenient scope-enforcement mode\n * (the default) and by code paths that legitimately run outside a request.\n */\nexport function tryGetRequester(): RequesterContext | undefined {\n return als.getStore();\n}\n\n/**\n * Resolve the effective scope for the ambient context, defaulting to `'user'`.\n */\nexport function requireRequesterScope(): RequesterScope {\n return requireRequester().scope ?? 'user';\n}\n\n/**\n * Convenience helpers for setting scope explicitly. All three preserve\n * `userId` in the context (audit trail) regardless of scope.\n *\n * - `withUserScope`: regular end-user requests. Most call sites.\n * - `withOrgScope`: admin / org-shared resource access. The caller MUST verify\n * the requester's role permits `'org'` before calling — the helper does not\n * enforce authorization. `orgUserIds` is pre-resolved at the boundary.\n * - `withSuperuserScope`: engineering scripts / internal tools. `organizationId`\n * is null (cross-org is the point). Same authorization caveat applies.\n */\nexport function withUserScope<T>(\n userId: string,\n organizationId: string | null,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester({ userId, organizationId, scope: 'user' }, fn);\n}\n\nexport function withOrgScope<T>(\n userId: string,\n organizationId: string,\n orgUserIds: readonly string[],\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId, scope: 'org', orgUserIds },\n fn,\n );\n}\n\nexport function withSuperuserScope<T>(\n userId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId: null, scope: 'superuser' },\n fn,\n );\n}\n"],"mappings":";AAWA,SAAS,KAAK,IAAI,SAAS,QAAQ,WAAW;;;ACiC9C,SAAS,yBAAyB;AA6ClC,IAAM,MAAM,IAAI,kBAAoC;AAmB7C,SAAS,mBAAqC;AACnD,QAAM,MAAM,IAAI,SAAS;AACzB,MAAI,CAAC,KAAK;AACR,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,SAAO;AACT;AAOO,SAAS,kBAAgD;AAC9D,SAAO,IAAI,SAAS;AACtB;;;AD7EO,IAAe,iBAAf,MAAuC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWzB,YAA4B;AAAA,IAC7C,YAAY;AAAA,IACZ,YAAY;AAAA,IACZ,cAAc;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAemB,mBAAyC;AAAA,EAEzC;AAAA,EAEnB,YAAY,IAAmB;AAC7B,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASU,OAAO,IAA+B;AAC9C,WAAO,MAAM,KAAK;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,SAAS,IAAqC;AAClD,UAAM,OAAO,MAAM,KAAK,UAAU,GAAG,KAAK,MAAM,IAAI,GAAG,EAAE,CAAC,EAAE,MAAM,CAAC;AACnE,WAAQ,KAAK,CAAC,KAAiB;AAAA,EACjC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,UAAU,KAAmC;AACjD,QAAI,IAAI,WAAW,EAAG,QAAO,CAAC;AAC9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AA;AAAA;AAAA,EASU,eACR,OACA,MACyB;AACzB,QAAI,CAAC,KAAK,UAAU,WAAY,QAAO;AACvC,UAAM,MAAM,oBAAI,KAAK;AACrB,QAAI,SAAS,UAAU;AACrB,aAAO,EAAE,GAAG,OAAO,WAAW,KAAK,WAAW,IAAI;AAAA,IACpD;AACA,WAAO,EAAE,GAAG,OAAO,WAAW,IAAI;AAAA,EACpC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAwBU,mBACR,aACA,gBACK;AACL,WAAO;AAAA,sBACW,WAAW;AAAA,qBACZ,cAAc;AAAA;AAAA;AAAA,EAGjC;AACF;","names":[]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { BaseRepository, BehaviorConfig, ListOptions } from './base-repository.js';
|
|
2
|
+
export { RequesterContext, RequesterScope, requireRequester, requireRequesterScope, tryGetRequester, withOrgScope, withRequester, withSuperuserScope, withUserScope } from './tenant-context.js';
|
|
2
3
|
export { BaseService, IBaseRepository } from './base-service.js';
|
|
3
4
|
export { EventCategory, buildChangeEvents, buildLifecycleEvent, diffSnapshots, emitSafely, entitySnapshot } from './lifecycle-events.js';
|
|
4
5
|
export { BaseFindByIdUseCase, BaseListUseCase, IFindByIdService, IListService } from './base-read-use-cases.js';
|
|
@@ -1,5 +1,44 @@
|
|
|
1
1
|
// runtime/base-classes/base-repository.ts
|
|
2
|
-
import { eq, inArray, isNull, sql } from "drizzle-orm";
|
|
2
|
+
import { and, eq, inArray, isNull, sql } from "drizzle-orm";
|
|
3
|
+
|
|
4
|
+
// runtime/base-classes/tenant-context.ts
|
|
5
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
6
|
+
var als = new AsyncLocalStorage();
|
|
7
|
+
function withRequester(ctx, fn) {
|
|
8
|
+
return als.run(ctx, fn);
|
|
9
|
+
}
|
|
10
|
+
function requireRequester() {
|
|
11
|
+
const ctx = als.getStore();
|
|
12
|
+
if (!ctx) {
|
|
13
|
+
throw new Error(
|
|
14
|
+
"No requester context active. Wrap the entry point in withRequester({ userId, organizationId }, fn). See tenant-context.ts."
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
return ctx;
|
|
18
|
+
}
|
|
19
|
+
function tryGetRequester() {
|
|
20
|
+
return als.getStore();
|
|
21
|
+
}
|
|
22
|
+
function requireRequesterScope() {
|
|
23
|
+
return requireRequester().scope ?? "user";
|
|
24
|
+
}
|
|
25
|
+
function withUserScope(userId, organizationId, fn) {
|
|
26
|
+
return withRequester({ userId, organizationId, scope: "user" }, fn);
|
|
27
|
+
}
|
|
28
|
+
function withOrgScope(userId, organizationId, orgUserIds, fn) {
|
|
29
|
+
return withRequester(
|
|
30
|
+
{ userId, organizationId, scope: "org", orgUserIds },
|
|
31
|
+
fn
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
function withSuperuserScope(userId, fn) {
|
|
35
|
+
return withRequester(
|
|
36
|
+
{ userId, organizationId: null, scope: "superuser" },
|
|
37
|
+
fn
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// runtime/base-classes/base-repository.ts
|
|
3
42
|
var BaseRepository = class {
|
|
4
43
|
// eslint-disable-line @typescript-eslint/no-explicit-any
|
|
5
44
|
/**
|
|
@@ -11,6 +50,20 @@ var BaseRepository = class {
|
|
|
11
50
|
softDelete: false,
|
|
12
51
|
userTracking: false
|
|
13
52
|
};
|
|
53
|
+
/**
|
|
54
|
+
* Ambient tenant-scope enforcement for `userTracking` repos (see
|
|
55
|
+
* `scopePredicate`). Only has effect when `behaviors.userTracking === true`.
|
|
56
|
+
*
|
|
57
|
+
* - `'lenient'` (default): when no ambient requester context is active,
|
|
58
|
+
* reads/writes are NOT scoped — preserves pre-scoping behavior, so adopting
|
|
59
|
+
* ambient scoping is additive. Scoping kicks in automatically once a
|
|
60
|
+
* boundary installs `withRequester(...)`.
|
|
61
|
+
* - `'strict'`: a missing ambient context throws (`requireRequester`),
|
|
62
|
+
* making a forgotten boundary fail loud instead of silently returning
|
|
63
|
+
* cross-tenant rows. Recommended for new multi-tenant consumers — override
|
|
64
|
+
* in a concrete repo or a family base class.
|
|
65
|
+
*/
|
|
66
|
+
scopeEnforcement = "lenient";
|
|
14
67
|
db;
|
|
15
68
|
constructor(db) {
|
|
16
69
|
this.db = db;
|
|
@@ -33,7 +86,7 @@ var BaseRepository = class {
|
|
|
33
86
|
* Returns null if not found (or soft-deleted when softDelete=true).
|
|
34
87
|
*/
|
|
35
88
|
async findById(id) {
|
|
36
|
-
const rows = await this.baseQuery(
|
|
89
|
+
const rows = await this.baseQuery(eq(this.table["id"], id)).limit(1);
|
|
37
90
|
return rows[0] ?? null;
|
|
38
91
|
}
|
|
39
92
|
/**
|
|
@@ -42,17 +95,14 @@ var BaseRepository = class {
|
|
|
42
95
|
*/
|
|
43
96
|
async findByIds(ids) {
|
|
44
97
|
if (ids.length === 0) return [];
|
|
45
|
-
const rows = await this.baseQuery(
|
|
98
|
+
const rows = await this.baseQuery(inArray(this.table["id"], ids));
|
|
46
99
|
return rows;
|
|
47
100
|
}
|
|
48
101
|
/**
|
|
49
102
|
* List entities with optional filtering, pagination, and ordering.
|
|
50
103
|
*/
|
|
51
104
|
async list(options) {
|
|
52
|
-
let query = this.baseQuery();
|
|
53
|
-
if (options?.where) {
|
|
54
|
-
query = query.where(options.where);
|
|
55
|
-
}
|
|
105
|
+
let query = this.baseQuery(options?.where);
|
|
56
106
|
if (options?.orderBy) {
|
|
57
107
|
query = query.orderBy(options.orderBy);
|
|
58
108
|
}
|
|
@@ -75,14 +125,17 @@ var BaseRepository = class {
|
|
|
75
125
|
if (this.behaviors.softDelete) {
|
|
76
126
|
conditions.push(isNull(this.table["deletedAt"]));
|
|
77
127
|
}
|
|
128
|
+
const scope = this.scopePredicate();
|
|
129
|
+
if (scope) {
|
|
130
|
+
conditions.push(scope);
|
|
131
|
+
}
|
|
78
132
|
if (where) {
|
|
79
133
|
conditions.push(where);
|
|
80
134
|
}
|
|
81
135
|
if (conditions.length === 1) {
|
|
82
136
|
query = query.where(conditions[0]);
|
|
83
137
|
} else if (conditions.length > 1) {
|
|
84
|
-
|
|
85
|
-
query = query.where(and4(...conditions));
|
|
138
|
+
query = query.where(and(...conditions));
|
|
86
139
|
}
|
|
87
140
|
const rows = await query;
|
|
88
141
|
return rows[0]?.count ?? 0;
|
|
@@ -111,7 +164,7 @@ var BaseRepository = class {
|
|
|
111
164
|
*/
|
|
112
165
|
async update(id, input, tx) {
|
|
113
166
|
const data = this.withTimestamps(input, "update");
|
|
114
|
-
const rows = await this.runner(tx).update(this.table).set(data).where(eq(this.table["id"], id)).returning();
|
|
167
|
+
const rows = await this.runner(tx).update(this.table).set(data).where(this.scopeAnd(eq(this.table["id"], id))).returning();
|
|
115
168
|
return rows[0];
|
|
116
169
|
}
|
|
117
170
|
/**
|
|
@@ -122,9 +175,9 @@ var BaseRepository = class {
|
|
|
122
175
|
async delete(id, tx) {
|
|
123
176
|
const runner = this.runner(tx);
|
|
124
177
|
if (this.behaviors.softDelete) {
|
|
125
|
-
await runner.update(this.table).set({ deletedAt: /* @__PURE__ */ new Date() }).where(eq(this.table["id"], id));
|
|
178
|
+
await runner.update(this.table).set({ deletedAt: /* @__PURE__ */ new Date() }).where(this.scopeAnd(eq(this.table["id"], id)));
|
|
126
179
|
} else {
|
|
127
|
-
await runner.delete(this.table).where(eq(this.table["id"], id));
|
|
180
|
+
await runner.delete(this.table).where(this.scopeAnd(eq(this.table["id"], id)));
|
|
128
181
|
}
|
|
129
182
|
}
|
|
130
183
|
/**
|
|
@@ -139,15 +192,64 @@ var BaseRepository = class {
|
|
|
139
192
|
// Protected Helpers
|
|
140
193
|
// ============================================================================
|
|
141
194
|
/**
|
|
142
|
-
* Base SELECT query that automatically
|
|
143
|
-
* when softDelete
|
|
195
|
+
* Base SELECT query that automatically applies the ambient guards —
|
|
196
|
+
* soft-delete exclusion (when `softDelete`) and tenant scope (when
|
|
197
|
+
* `userTracking` + an active requester context) — combined with an optional
|
|
198
|
+
* caller `extra` predicate into a SINGLE `WHERE`.
|
|
199
|
+
*
|
|
200
|
+
* Pass the leaf predicate as `extra` rather than chaining a second
|
|
201
|
+
* `.where(...)`: Drizzle's `.where()` OVERRIDES (does not AND) a prior
|
|
202
|
+
* `.where()` on a `$dynamic()` query, so a chained call would silently drop
|
|
203
|
+
* the soft-delete and scope guards. `baseQuery(extra)` is the safe form.
|
|
144
204
|
*/
|
|
145
|
-
baseQuery() {
|
|
205
|
+
baseQuery(extra) {
|
|
146
206
|
const query = this.db.select().from(this.table).$dynamic();
|
|
147
|
-
|
|
148
|
-
|
|
207
|
+
const where = this.scopeAnd(extra, { softDelete: this.behaviors.softDelete });
|
|
208
|
+
return where ? query.where(where) : query;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Build the ambient tenant-scope predicate for this repo's table.
|
|
212
|
+
*
|
|
213
|
+
* Returns `undefined` (no scoping) when:
|
|
214
|
+
* - `behaviors.userTracking` is false (repo is not user-owned), or
|
|
215
|
+
* - no ambient requester context is active AND `scopeEnforcement` is
|
|
216
|
+
* `'lenient'` (the default — preserves pre-scoping behavior).
|
|
217
|
+
*
|
|
218
|
+
* When a requester context is active, scopes by `user_id` per the ambient
|
|
219
|
+
* scope: `'user'` → `user_id = ctx.userId`; `'org'` → `user_id IN
|
|
220
|
+
* ctx.orgUserIds` (empty list matches nothing — fail-closed); `'superuser'`
|
|
221
|
+
* → no filter. See `tenant-context.ts` for the boundary-install contract.
|
|
222
|
+
*/
|
|
223
|
+
scopePredicate() {
|
|
224
|
+
if (!this.behaviors.userTracking) return void 0;
|
|
225
|
+
const ctx = this.scopeEnforcement === "strict" ? requireRequester() : tryGetRequester();
|
|
226
|
+
if (!ctx) return void 0;
|
|
227
|
+
const scope = ctx.scope ?? "user";
|
|
228
|
+
switch (scope) {
|
|
229
|
+
case "superuser":
|
|
230
|
+
return void 0;
|
|
231
|
+
case "org":
|
|
232
|
+
return ctx.orgUserIds && ctx.orgUserIds.length > 0 ? inArray(this.table["userId"], ctx.orgUserIds) : sql`false`;
|
|
233
|
+
case "user":
|
|
234
|
+
default:
|
|
235
|
+
return eq(this.table["userId"], ctx.userId);
|
|
149
236
|
}
|
|
150
|
-
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Combine the ambient scope predicate (and, optionally, the soft-delete
|
|
240
|
+
* guard) with a caller `extra` predicate into one `SQL`. Returns `undefined`
|
|
241
|
+
* when nothing applies. Used by read + by-id write paths so a single
|
|
242
|
+
* `.where(...)` carries every guard.
|
|
243
|
+
*/
|
|
244
|
+
scopeAnd(extra, opts) {
|
|
245
|
+
const conditions = [];
|
|
246
|
+
if (opts?.softDelete) conditions.push(isNull(this.table["deletedAt"]));
|
|
247
|
+
const scope = this.scopePredicate();
|
|
248
|
+
if (scope) conditions.push(scope);
|
|
249
|
+
if (extra) conditions.push(extra);
|
|
250
|
+
if (conditions.length === 0) return void 0;
|
|
251
|
+
if (conditions.length === 1) return conditions[0];
|
|
252
|
+
return and(...conditions);
|
|
151
253
|
}
|
|
152
254
|
/**
|
|
153
255
|
* Merge timestamp fields into an input object.
|
|
@@ -409,7 +511,7 @@ var BaseListUseCase = class {
|
|
|
409
511
|
};
|
|
410
512
|
|
|
411
513
|
// runtime/base-classes/synced-entity-repository.ts
|
|
412
|
-
import { and, eq as eq2, inArray as inArray2 } from "drizzle-orm";
|
|
514
|
+
import { and as and2, eq as eq2, inArray as inArray2 } from "drizzle-orm";
|
|
413
515
|
var SyncedEntityRepository = class extends BaseRepository {
|
|
414
516
|
/**
|
|
415
517
|
* Find a single entity by its external CRM identifier.
|
|
@@ -506,7 +608,7 @@ var SyncedEntityRepository = class extends BaseRepository {
|
|
|
506
608
|
*/
|
|
507
609
|
async findByExternalIdProjected(externalId, provider) {
|
|
508
610
|
const rows = await this.db.select().from(this.table).where(
|
|
509
|
-
|
|
611
|
+
and2(
|
|
510
612
|
eq2(this.table["provider"], provider),
|
|
511
613
|
eq2(this.table["externalId"], externalId)
|
|
512
614
|
)
|
|
@@ -524,7 +626,7 @@ var SyncedEntityRepository = class extends BaseRepository {
|
|
|
524
626
|
const db = this.runner(tx);
|
|
525
627
|
const set = this.syncConfig.softDelete ? { deletedAt: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date() } : { externalId: null, provider: null, updatedAt: /* @__PURE__ */ new Date() };
|
|
526
628
|
const rows = await db.update(this.table).set(set).where(
|
|
527
|
-
|
|
629
|
+
and2(
|
|
528
630
|
eq2(this.table["provider"], provider),
|
|
529
631
|
eq2(this.table["externalId"], externalId)
|
|
530
632
|
)
|
|
@@ -593,7 +695,7 @@ var SyncedEntityRepository = class extends BaseRepository {
|
|
|
593
695
|
}
|
|
594
696
|
const refTable = fk.refTable === "self" ? this.table : fk.refTable;
|
|
595
697
|
const rows = await db.select({ id: refTable["id"] }).from(refTable).where(
|
|
596
|
-
|
|
698
|
+
and2(
|
|
597
699
|
eq2(refTable["provider"], provider),
|
|
598
700
|
eq2(refTable["externalId"], parentExternalId)
|
|
599
701
|
)
|
|
@@ -616,7 +718,7 @@ var SyncedEntityRepository = class extends BaseRepository {
|
|
|
616
718
|
};
|
|
617
719
|
|
|
618
720
|
// runtime/base-classes/junction-sync-repository.ts
|
|
619
|
-
import { and as
|
|
721
|
+
import { and as and3, eq as eq3 } from "drizzle-orm";
|
|
620
722
|
var JunctionSyncRepository = class extends BaseRepository {
|
|
621
723
|
/**
|
|
622
724
|
* Upsert ONE junction row by its composite identity, in a single transaction:
|
|
@@ -746,7 +848,7 @@ var JunctionSyncRepository = class extends BaseRepository {
|
|
|
746
848
|
if (cfg.roleColumn && role !== void 0) {
|
|
747
849
|
conds.push(eq3(this.table[cfg.roleColumn], role));
|
|
748
850
|
}
|
|
749
|
-
return
|
|
851
|
+
return and3(...conds);
|
|
750
852
|
}
|
|
751
853
|
/** Resolve a parent id (provider-scoped), throwing when unresolved. */
|
|
752
854
|
async resolveStrict(db, refTable, parentExternalId, provider, column) {
|
|
@@ -762,7 +864,7 @@ var JunctionSyncRepository = class extends BaseRepository {
|
|
|
762
864
|
async resolveLoose(db, refTable, parentExternalId, provider) {
|
|
763
865
|
if (!parentExternalId) return null;
|
|
764
866
|
const rows = await db.select({ id: refTable["id"] }).from(refTable).where(
|
|
765
|
-
|
|
867
|
+
and3(
|
|
766
868
|
eq3(refTable["provider"], provider),
|
|
767
869
|
eq3(refTable["externalId"], parentExternalId)
|
|
768
870
|
)
|
|
@@ -818,7 +920,7 @@ var ActivityEntityRepository = class extends BaseRepository {
|
|
|
818
920
|
};
|
|
819
921
|
|
|
820
922
|
// runtime/base-classes/metadata-entity-repository.ts
|
|
821
|
-
import { eq as eq5, and as
|
|
923
|
+
import { eq as eq5, and as and4, desc as desc2 } from "drizzle-orm";
|
|
822
924
|
var MetadataEntityRepository = class extends BaseRepository {
|
|
823
925
|
/**
|
|
824
926
|
* Bulk upsert with a caller-specified conflict target.
|
|
@@ -845,7 +947,7 @@ var MetadataEntityRepository = class extends BaseRepository {
|
|
|
845
947
|
*/
|
|
846
948
|
async findByEntityIdAndType(entityId, entityType) {
|
|
847
949
|
const rows = await this.baseQuery().where(
|
|
848
|
-
|
|
950
|
+
and4(
|
|
849
951
|
eq5(this.table["entityId"], entityId),
|
|
850
952
|
eq5(this.table["entityType"], entityType)
|
|
851
953
|
)
|
|
@@ -993,6 +1095,13 @@ export {
|
|
|
993
1095
|
diffSnapshots,
|
|
994
1096
|
emitSafely,
|
|
995
1097
|
entitySnapshot,
|
|
996
|
-
parseCompositeExternalId
|
|
1098
|
+
parseCompositeExternalId,
|
|
1099
|
+
requireRequester,
|
|
1100
|
+
requireRequesterScope,
|
|
1101
|
+
tryGetRequester,
|
|
1102
|
+
withOrgScope,
|
|
1103
|
+
withRequester,
|
|
1104
|
+
withSuperuserScope,
|
|
1105
|
+
withUserScope
|
|
997
1106
|
};
|
|
998
1107
|
//# sourceMappingURL=index.js.map
|