@venizia/ignis-connectors 0.4.8-1 → 0.4.8-3
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/README.md +4 -2
- package/dist/esm/common/internal/index.d.ts +0 -1
- package/dist/esm/common/internal/index.js +0 -1
- package/dist/esm/common/internal/index.js.map +1 -1
- package/dist/esm/relational/core/repositories/common/scope-write-guard.js +5 -6
- package/dist/esm/relational/core/repositories/common/scope-write-guard.js.map +1 -1
- package/dist/esm/relational/core/repositories/core/base.js +2 -1
- package/dist/esm/relational/core/repositories/core/base.js.map +1 -1
- package/dist/esm/relational/core/repositories/dialect/filter.d.ts +2 -1
- package/dist/esm/relational/core/repositories/dialect/filter.js +19 -2
- package/dist/esm/relational/core/repositories/dialect/filter.js.map +1 -1
- package/dist/esm/search/core/internal/search-connector-internal.js +1 -2
- package/dist/esm/search/core/internal/search-connector-internal.js.map +1 -1
- package/dist/esm/search/meilisearch/connector.js +1 -2
- package/dist/esm/search/meilisearch/connector.js.map +1 -1
- package/dist/esm/search/meilisearch/internal/connector-internal.js +1 -1
- package/dist/esm/search/meilisearch/internal/connector-internal.js.map +1 -1
- package/dist/esm/search/typesense/connector.js +1 -2
- package/dist/esm/search/typesense/connector.js.map +1 -1
- package/dist/esm/search/typesense/internal/guards.js +1 -1
- package/dist/esm/search/typesense/internal/guards.js.map +1 -1
- package/dist/esm/search/typesense/internal/mappers.js +1 -1
- package/dist/esm/search/typesense/internal/mappers.js.map +1 -1
- package/package.json +6 -6
- package/dist/esm/common/internal/record.d.ts +0 -5
- package/dist/esm/common/internal/record.js +0 -7
- package/dist/esm/common/internal/record.js.map +0 -1
package/README.md
CHANGED
|
@@ -4,8 +4,8 @@ The datasources, drivers, entity bases and repositories IGNIS uses to reach a ba
|
|
|
4
4
|
through Drizzle (Postgres, PGlite, SQLite), search engines (Typesense, Meilisearch), and another
|
|
5
5
|
IGNIS server over HTTP.
|
|
6
6
|
|
|
7
|
-
Server applications get
|
|
8
|
-
directly when you use the connectors without the server, for example in a browser Worker.
|
|
7
|
+
Server applications get the Postgres entry through `@venizia/ignis`; every other entry is imported from this
|
|
8
|
+
package. Install it directly when you use the connectors without the server, for example in a browser Worker.
|
|
9
9
|
|
|
10
10
|
## Install
|
|
11
11
|
|
|
@@ -123,6 +123,8 @@ styles can live in one application.
|
|
|
123
123
|
| `/typesense/controllers` | The same search controllers as `/search/controllers` | `hono`, `@hono/zod-openapi` |
|
|
124
124
|
| `/meilisearch` | `MeilisearchDataSource`, `MeilisearchConnector`, `MeilisearchQueryDialect` | `meilisearch` |
|
|
125
125
|
| `/http` | `HttpDataSource` and `HttpRepository` - read another IGNIS server's REST routes with the same filter vocabulary | none |
|
|
126
|
+
| `/raw-sql` | `BaseRawSqlDataSource`, `BaseRawSqlRepository`, `RawSqlEntity` - an engine that only runs raw SQL and returns rows, with no dialect and no transactions; you supply the connector and the driver | none to load (`drizzle-orm` for the `SQLWrapper` type) |
|
|
127
|
+
| `/testing` | Test-only: `RepositoryDouble`, `TransactionDouble`, `PostgresTransactionDouble`, `SqliteTransactionDouble`; never imported from a production barrel | none |
|
|
126
128
|
|
|
127
129
|
The root entry imports no driver and no engine client. A driver loads only when you import its
|
|
128
130
|
entry and name its class in `@datasource({ driver })`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/common/internal/index.ts"],"names":[],"mappings":"AAAA,cAAc,QAAQ,CAAC
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/common/internal/index.ts"],"names":[],"mappings":"AAAA,cAAc,QAAQ,CAAC","sourcesContent":["export * from './echo';\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getError } from '@venizia/ignis-helpers/core';
|
|
1
|
+
import { getError, RecordUtility } from '@venizia/ignis-helpers/core';
|
|
2
2
|
import { QueryOperators, RepositoryErrorCodes, ScopeFilterMissingBehaviors, ScopeFilters, ScopeOperations, ScopeWriteGuards, } from '@venizia/ignis-kernel';
|
|
3
3
|
import { HTTP } from '@venizia/ignis-helpers/common';
|
|
4
4
|
import { ScopeFilterDenial } from './scope-filter.js';
|
|
@@ -8,9 +8,6 @@ const isScalar = (value) => {
|
|
|
8
8
|
value instanceof Date ||
|
|
9
9
|
['string', 'number', 'bigint', 'boolean'].includes(typeof value));
|
|
10
10
|
};
|
|
11
|
-
const isRecord = (value) => {
|
|
12
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
13
|
-
};
|
|
14
11
|
const normalise = (value) => {
|
|
15
12
|
if (value === null) {
|
|
16
13
|
return null;
|
|
@@ -190,7 +187,9 @@ export class ScopeWriteGuard {
|
|
|
190
187
|
}
|
|
191
188
|
const kept = [];
|
|
192
189
|
for (const part of value) {
|
|
193
|
-
const narrowed = ScopeWriteGuard.withoutShared({
|
|
190
|
+
const narrowed = ScopeWriteGuard.withoutShared({
|
|
191
|
+
where: RecordUtility.isPlainRecord(part) ? part : {},
|
|
192
|
+
});
|
|
194
193
|
if (narrowed.kind === 'unverifiable') {
|
|
195
194
|
return narrowed;
|
|
196
195
|
}
|
|
@@ -243,7 +242,7 @@ export class ScopeWriteGuard {
|
|
|
243
242
|
if (Array.isArray(value)) {
|
|
244
243
|
return list(value);
|
|
245
244
|
}
|
|
246
|
-
if (!
|
|
245
|
+
if (!RecordUtility.isPlainRecord(value)) {
|
|
247
246
|
return { kind: 'unverifiable', reason: 'an unsupported condition' };
|
|
248
247
|
}
|
|
249
248
|
const operators = Object.keys(value);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scope-write-guard.js","sourceRoot":"","sources":["../../../../../../src/relational/core/repositories/common/scope-write-guard.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,2BAA2B,EAC3B,YAAY,EACZ,eAAe,EACf,gBAAgB,GACjB,M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AE,+EAA+E,KAAK,iBAAiB,SAAS,EAAE;SAC1H,CAAC,CAAC;IACL,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,YAAY,CAAC,IAAmE;QACrF,OAAO,eAAe,CAAC,MAAM,CAAC;YAC5B,GAAG,IAAI;YACP,MAAM,EAAE,qDAAqD;SAC9D,CAAC,CAAC;IACL,CAAC;IAED,kFAAkF;IAC1E,MAAM,CAAC,MAAM,CAAC,IAKrB;QACC,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAElD,OAAO,QAAQ,CAAC;YACd,UAAU,EAAE,mBAAmB;YAC/B,WAAW,EAAE,oBAAoB,CAAC,kBAAkB;YACpD,OAAO,EAAE;gBACP,IAAI,SAAS,iDAAiD,KAAK,EAAE;gBACrE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;gBACxC,MAAM;aACP,CAAC,IAAI,CAAC,KAAK,CAAC;SACd,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { getError } from '@venizia/ignis-helpers/core';\nimport {\n QueryOperators,\n RepositoryErrorCodes,\n ScopeFilterMissingBehaviors,\n ScopeFilters,\n ScopeOperations,\n ScopeWriteGuards,\n} from '@venizia/ignis-kernel';\nimport type {\n IModelAccessSettings,\n TModelAccessSettings,\n TScopeOperation,\n TWhere,\n} from '@venizia/ignis-kernel';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { ScopeFilterDenial } from './scope-filter';\n\ntype TScalar = string | number | bigint | boolean | Date | null;\n\n/** The allowed values per scope column, each normalised so `1` and `'1'` and equal dates compare equal. */\ntype TConstraints = Map<string, Set<string | null>>;\n\ntype TExtraction =\n | { isVerifiable: true; constraints: TConstraints }\n | { isVerifiable: false; reason: string };\n\n/** What the scope becomes for a write: a `where`, no row at all, or a shape that cannot be narrowed. */\ntype TNarrowed =\n | { kind: 'where'; where: TWhere }\n | { kind: 'none' }\n | { kind: 'unverifiable'; reason: string };\n\nconst WRITE_DENIED_STATUS = HTTP.ResultCodes.RS_4.Forbidden;\n\nconst isScalar = (value: unknown): value is TScalar => {\n return (\n value === null ||\n value instanceof Date ||\n ['string', 'number', 'bigint', 'boolean'].includes(typeof value)\n );\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n};\n\nconst normalise = (value: TScalar): string | null => {\n if (value === null) {\n return null;\n }\n\n return value instanceof Date ? value.toISOString() : String(value);\n};\n\nconst intersect = (opts: { left: Set<string | null>; right: Set<string | null> }) => {\n return new Set([...opts.left].filter((value) => opts.right.has(value)));\n};\n\n/**\n * The write side of `@model` settings.access. The resolved scope is a `where`; the guard reads\n * from it the columns it constrains and the values it allows, and holds every written row to them.\n *\n * Only shapes that can be checked are read: a column equal to a scalar or `null`, `{ eq }`, `{ inq }`\n * (or `in`), an array, `and` of those, and an `or` whose branches all constrain the same column. Anything\n * else - an `or` over several columns, ranges, `like`, a nested path - makes\n * the scope unverifiable, and the write is refused with its own message instead of being skipped.\n */\nexport class ScopeWriteGuard {\n static extractConstraints(opts: { where: TWhere }): TExtraction {\n const constraints: TConstraints = new Map();\n const reason = ScopeWriteGuard.collect({\n where: opts.where as Record<string, unknown>,\n constraints,\n });\n\n return reason === undefined\n ? { isVerifiable: true, constraints }\n : { isVerifiable: false, reason };\n }\n\n /** Adds the where's constraints to `constraints`; returns the reason it cannot be verified, if any. */\n private static collect(opts: {\n where: Record<string, unknown>;\n constraints: TConstraints;\n }): string | undefined {\n const { where, constraints } = opts;\n\n for (const [key, value] of Object.entries(where)) {\n if (key === 'and') {\n if (!Array.isArray(value)) {\n return \"'and' is not a list\";\n }\n\n for (const part of value) {\n const reason = ScopeWriteGuard.collect({\n where: part as Record<string, unknown>,\n constraints,\n });\n\n if (reason !== undefined) {\n return reason;\n }\n }\n\n continue;\n }\n\n if (key === 'or') {\n const union = ScopeWriteGuard.unionOfBranches({ branches: value });\n\n if (typeof union === 'string') {\n return union;\n }\n\n const existing = constraints.get(union.column);\n constraints.set(\n union.column,\n existing ? intersect({ left: existing, right: union.allowed }) : union.allowed,\n );\n continue;\n }\n\n if (key.includes('.')) {\n return `the nested path '${key}' cannot be checked on a write`;\n }\n\n const allowed = ScopeWriteGuard.allowedValues({ value });\n\n if (typeof allowed === 'string') {\n return `column '${key}': ${allowed}`;\n }\n\n const existing = constraints.get(key);\n constraints.set(key, existing ? intersect({ left: existing, right: allowed }) : allowed);\n }\n\n return undefined;\n }\n\n /**\n * An `or` is checkable only when every branch constrains the same single column with a scalar,\n * `null`, `eq`, `in` or `inq`: the allowed values are then the union of the branches. This is the\n * shared-rows scope, `{ or: [{ merchantId: { in: ids } }, { merchantId: null }] }`. Any other `or`\n * (several columns, ranges, nested `and` or `or`) cannot be checked.\n */\n private static unionOfBranches(opts: {\n branches: unknown;\n }): { column: string; allowed: Set<string | null> } | string {\n const { branches } = opts;\n\n if (!Array.isArray(branches) || branches.length === 0) {\n return \"'or' is not a list\";\n }\n\n let column: string | undefined;\n const allowed = new Set<string | null>();\n\n for (const branch of branches) {\n const entries = Object.entries((branch ?? {}) as Record<string, unknown>);\n\n if (entries.length !== 1) {\n return \"an 'or' branch with several conditions cannot be checked on a write\";\n }\n\n const [key, value] = entries[0];\n\n if (key === 'and' || key === 'or' || key.includes('.')) {\n return `an 'or' branch over '${key}' cannot be checked on a write`;\n }\n\n if (column !== undefined && column !== key) {\n return \"an 'or' over different columns cannot be checked on a write\";\n }\n\n column = key;\n const values = ScopeWriteGuard.allowedValues({ value });\n\n if (typeof values === 'string') {\n return `column '${key}': ${values}`;\n }\n\n values.forEach((entry) => allowed.add(entry));\n }\n\n return { column: column as string, allowed };\n }\n\n /** The values one column's condition allows, or a string naming why it cannot be checked. */\n private static allowedValues(opts: { value: unknown }): Set<string | null> | string {\n const { value } = opts;\n\n if (isScalar(value)) {\n return new Set([normalise(value)]);\n }\n\n if (Array.isArray(value)) {\n return value.every(isScalar)\n ? new Set(value.map(normalise))\n : 'a list with a non-scalar entry';\n }\n\n if (typeof value !== 'object' || value === undefined) {\n return 'an unsupported condition';\n }\n\n const operators = Object.keys(value as object);\n\n if (operators.length !== 1) {\n return `a condition with ${operators.length} operators cannot be checked on a write`;\n }\n\n const [operator] = operators;\n const operand = (value as Record<string, unknown>)[operator];\n\n if (operator === QueryOperators.EQ && isScalar(operand)) {\n return new Set([normalise(operand)]);\n }\n\n if (\n (operator === QueryOperators.INQ || operator === QueryOperators.IN) &&\n Array.isArray(operand)\n ) {\n return operand.every(isScalar)\n ? new Set(operand.map(normalise))\n : 'a list with a non-scalar entry';\n }\n\n return `the operator '${operator}' cannot be checked on a write`;\n }\n\n /**\n * The scope as a MUTATION `where` (update, delete, soft delete, restore). A scope with a `null`\n * branch - `{ or: [{ merchantId: { in: ids } }, { merchantId: null }] }` - lets the caller READ the\n * shared rows. Changing or deleting one is the same permission as creating one, `write.sharedRows`,\n * so without it the `null` branch is removed and only the caller's own rows match. With\n * `sharedRows` the scope is returned as it is.\n *\n * Only the shapes the write guard can read are narrowed. Any other shape cannot be shown to exclude\n * the shared rows, so the mutation is refused, as an update with a payload already is.\n */\n static mutationWhere(opts: {\n settings: TModelAccessSettings;\n model: string;\n operation: TScopeOperation;\n scopeWhere: TWhere;\n }): TWhere {\n const { settings, model, operation, scopeWhere } = opts;\n\n ScopeWriteGuard.assertWrite({ model, operation });\n\n // Checked with `sharedRows` too: it lets the null branch through, not a shape the guard cannot read.\n const narrowed = ScopeWriteGuard.withoutShared({ where: scopeWhere });\n\n if (narrowed.kind === 'unverifiable') {\n throw ScopeWriteGuard.denied({\n model,\n operation,\n detail: `the resolved scope cannot be verified on a write | ${narrowed.reason}`,\n });\n }\n\n if (settings.write?.sharedRows === true) {\n return scopeWhere;\n }\n\n return narrowed.kind === 'none' ? ScopeFilterDenial.where() : narrowed.where;\n }\n\n /** `where` with every `null` the scope allows removed; `none` when nothing but `null` was allowed. */\n private static withoutShared(opts: { where: TWhere }): TNarrowed {\n const result: TWhere = {};\n\n for (const [key, value] of Object.entries(opts.where)) {\n if (key === 'and' || key === 'or') {\n if (!Array.isArray(value) || (key === 'or' && value.length === 0)) {\n return { kind: 'unverifiable', reason: `'${key}' is not a list` };\n }\n\n // An 'or' is read only when every branch constrains the same column, as the guard reads it: a branch over another column\n // could match a shared row without a null in sight.\n if (key === 'or') {\n const union = ScopeWriteGuard.unionOfBranches({ branches: value });\n\n if (typeof union === 'string') {\n return { kind: 'unverifiable', reason: union };\n }\n }\n\n const kept: TWhere[] = [];\n\n for (const part of value) {\n const narrowed = ScopeWriteGuard.withoutShared({ where: isRecord(part) ? part : {} });\n\n if (narrowed.kind === 'unverifiable') {\n return narrowed;\n }\n\n if (narrowed.kind === 'none') {\n // One impossible 'and' part makes the whole 'and' impossible; an impossible 'or' branch just drops out.\n if (key === 'and') {\n return narrowed;\n }\n\n continue;\n }\n\n kept.push(narrowed.where);\n }\n\n if (key === 'or' && kept.length === 0) {\n return { kind: 'none' };\n }\n\n result[key] = kept;\n continue;\n }\n\n if (key.includes('.')) {\n return {\n kind: 'unverifiable',\n reason: `the nested path '${key}' cannot be checked on a write`,\n };\n }\n\n const narrowed = ScopeWriteGuard.conditionWithoutNull({ value });\n\n if (narrowed.kind !== 'condition') {\n return narrowed.kind === 'none'\n ? { kind: 'none' }\n : { kind: 'unverifiable', reason: `column '${key}': ${narrowed.reason}` };\n }\n\n result[key] = narrowed.value;\n }\n\n return { kind: 'where', where: result };\n }\n\n /** One column's condition without its `null` values, reading the same shapes `allowedValues` reads. */\n private static conditionWithoutNull(opts: {\n value: unknown;\n }):\n | { kind: 'condition'; value: unknown }\n | { kind: 'none' }\n | { kind: 'unverifiable'; reason: string } {\n const { value } = opts;\n\n const list = (entries: unknown[]) => {\n if (!entries.every(isScalar)) {\n return { kind: 'unverifiable' as const, reason: 'a list with a non-scalar entry' };\n }\n\n const kept = entries.filter((entry) => entry !== null);\n\n return kept.length === 0\n ? { kind: 'none' as const }\n : { kind: 'condition' as const, value: kept };\n };\n\n if (isScalar(value)) {\n return value === null ? { kind: 'none' } : { kind: 'condition', value };\n }\n\n if (Array.isArray(value)) {\n return list(value);\n }\n\n if (!isRecord(value)) {\n return { kind: 'unverifiable', reason: 'an unsupported condition' };\n }\n\n const operators = Object.keys(value);\n\n if (operators.length !== 1) {\n return {\n kind: 'unverifiable',\n reason: `a condition with ${operators.length} operators cannot be checked on a write`,\n };\n }\n\n const [operator] = operators;\n const operand = value[operator];\n\n if (operator === QueryOperators.EQ && isScalar(operand)) {\n return operand === null ? { kind: 'none' } : { kind: 'condition', value };\n }\n\n if (\n (operator === QueryOperators.INQ || operator === QueryOperators.IN) &&\n Array.isArray(operand)\n ) {\n const narrowed = list(operand);\n\n return narrowed.kind === 'condition'\n ? { kind: 'condition', value: { [operator]: narrowed.value } }\n : narrowed;\n }\n\n return {\n kind: 'unverifiable',\n reason: `the operator '${operator}' cannot be checked on a write`,\n };\n }\n\n /**\n * Holds `rows` to the scope `settings.resolve()` returns now. Returns the rows to write: the same\n * objects when nothing changes, copies with the scope columns filled in for `assign`. Throws, and\n * so writes nothing, when any row is outside the scope.\n */\n static apply<Row extends Record<string, unknown>>(opts: {\n settings: IModelAccessSettings;\n model: string;\n rows: Row[];\n operation: TScopeOperation;\n }): Row[] {\n const { settings, model, rows, operation } = opts;\n\n ScopeWriteGuard.assertWrite({ model, operation });\n\n const scope = settings.resolve({ operation });\n\n if (scope === ScopeFilters.UNRESTRICTED) {\n return rows;\n }\n\n if (scope === null || scope === undefined) {\n // An update is already confined by the scoped `where`, which under `deny` matches no row; the\n // guard adds nothing there. A create has no such `where`, so an unresolved scope refuses it.\n if (\n settings.onMissing === ScopeFilterMissingBehaviors.ALLOW ||\n operation !== ScopeOperations.CREATE\n ) {\n return rows;\n }\n\n throw ScopeWriteGuard.denied({\n model,\n operation,\n detail: 'no scope could be resolved for this caller',\n });\n }\n\n const extraction = ScopeWriteGuard.extractConstraints({ where: scope });\n\n if (!extraction.isVerifiable) {\n throw ScopeWriteGuard.denied({\n model,\n operation,\n detail: `the resolved scope cannot be verified on a write | ${extraction.reason}`,\n });\n }\n\n const { constraints } = extraction;\n const declared = settings.columns;\n\n if (declared) {\n const undeclared = [...constraints.keys()].find((column) => !declared.includes(column));\n\n if (undeclared !== undefined) {\n throw ScopeWriteGuard.denied({\n model,\n operation,\n detail: `the resolved scope constrains column '${undeclared}', which access.columns does not declare`,\n });\n }\n }\n\n const isAssign =\n settings.write?.mode === ScopeWriteGuards.ASSIGN && operation === ScopeOperations.CREATE;\n const sharedRows = settings.write?.sharedRows === true;\n\n return rows.map((row) => {\n let result = row;\n\n for (const [column, allowed] of constraints) {\n const value = (row as Record<string, unknown>)[column];\n\n if (value === undefined) {\n if (operation !== ScopeOperations.CREATE) {\n continue;\n }\n\n // `assign` first: stamping gives the row an owner, which is safer than leaving it shared.\n const only = allowed.size === 1 ? [...allowed][0] : undefined;\n\n if (isAssign && only !== undefined && only !== null) {\n result = { ...result, [column]: only };\n continue;\n }\n\n // Absent means the database default, usually `null`, so it is held to the `null` rule.\n if (sharedRows) {\n continue;\n }\n\n throw ScopeWriteGuard.denied({\n model,\n operation,\n column,\n detail: 'the scope column is missing',\n });\n }\n\n const normalised = isScalar(value) ? normalise(value) : undefined;\n // A `null` branch in the scope lets this caller READ shared rows. Writing one (or moving a\n // row into the shared set) is a separate permission: only `sharedRows` grants it.\n const isOutside = normalised === null ? !sharedRows : !allowed.has(normalised as string);\n\n if (normalised === undefined || isOutside) {\n throw ScopeWriteGuard.denied({\n model,\n operation,\n column,\n detail: 'the value is outside the resolved scope',\n });\n }\n }\n\n return result;\n });\n }\n\n /**\n * The write guard runs for a write only. A READ reaching it is a bug in the caller, not a request,\n * so it throws a plain error rather than a refusal the caller could map to a status.\n */\n private static assertWrite(opts: { model: string; operation: TScopeOperation }): void {\n const { model, operation } = opts;\n\n if (ScopeOperations.includes({ group: ScopeOperations.WRITE, operation })) {\n return;\n }\n\n throw getError({\n message: `[ScopeWriteGuard] the write guard runs for a write operation only | entity: ${model} | operation: ${operation}`,\n });\n }\n\n /**\n * A write to a `through` model named no parent, a parent that does not exist, or one outside the caller's scope. One\n * message for all three, so a foreign parent's existence does not leak.\n */\n static parentDenied(opts: { model: string; operation: TScopeOperation; column: string }) {\n return ScopeWriteGuard.denied({\n ...opts,\n detail: \"the parent is missing or outside the caller's scope\",\n });\n }\n\n /** Names the model and the column, never a value: the caller may be a request. */\n private static denied(opts: {\n model: string;\n operation: TScopeOperation;\n column?: string;\n detail: string;\n }) {\n const { model, operation, column, detail } = opts;\n\n return getError({\n statusCode: WRITE_DENIED_STATUS,\n messageCode: RepositoryErrorCodes.SCOPE_WRITE_DENIED,\n message: [\n `[${operation}] write refused by the access scope | entity: ${model}`,\n ...(column ? [`column: ${column}`] : []),\n detail,\n ].join(' | '),\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"scope-write-guard.js","sourceRoot":"","sources":["../../../../../../src/relational/core/repositories/common/scope-write-guard.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,2BAA2B,EAC3B,YAAY,EACZ,eAAe,EACf,gBAAgB,GACjB,MAAM,uBAAuB,CAAC;AAO/B,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAiBnD,MAAM,mBAAmB,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC;AAE5D,MAAM,QAAQ,GAAG,CAAC,KAAc,EAAoB,EAAE;IACpD,OAAO,CACL,KAAK,KAAK,IAAI;QACd,KAAK,YAAY,IAAI;QACrB,CAAC,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC,QAAQ,CAAC,OAA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AC,WAAW,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;gBACxC,MAAM;aACP,CAAC,IAAI,CAAC,KAAK,CAAC;SACd,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { getError, RecordUtility } from '@venizia/ignis-helpers/core';\nimport {\n QueryOperators,\n RepositoryErrorCodes,\n ScopeFilterMissingBehaviors,\n ScopeFilters,\n ScopeOperations,\n ScopeWriteGuards,\n} from '@venizia/ignis-kernel';\nimport type {\n IModelAccessSettings,\n TModelAccessSettings,\n TScopeOperation,\n TWhere,\n} from '@venizia/ignis-kernel';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { ScopeFilterDenial } from './scope-filter';\n\ntype TScalar = string | number | bigint | boolean | Date | null;\n\n/** The allowed values per scope column, each normalised so `1` and `'1'` and equal dates compare equal. */\ntype TConstraints = Map<string, Set<string | null>>;\n\ntype TExtraction =\n | { isVerifiable: true; constraints: TConstraints }\n | { isVerifiable: false; reason: string };\n\n/** What the scope becomes for a write: a `where`, no row at all, or a shape that cannot be narrowed. */\ntype TNarrowed =\n | { kind: 'where'; where: TWhere }\n | { kind: 'none' }\n | { kind: 'unverifiable'; reason: string };\n\nconst WRITE_DENIED_STATUS = HTTP.ResultCodes.RS_4.Forbidden;\n\nconst isScalar = (value: unknown): value is TScalar => {\n return (\n value === null ||\n value instanceof Date ||\n ['string', 'number', 'bigint', 'boolean'].includes(typeof value)\n );\n};\n\nconst normalise = (value: TScalar): string | null => {\n if (value === null) {\n return null;\n }\n\n return value instanceof Date ? value.toISOString() : String(value);\n};\n\nconst intersect = (opts: { left: Set<string | null>; right: Set<string | null> }) => {\n return new Set([...opts.left].filter((value) => opts.right.has(value)));\n};\n\n/**\n * The write side of `@model` settings.access. The resolved scope is a `where`; the guard reads\n * from it the columns it constrains and the values it allows, and holds every written row to them.\n *\n * Only shapes that can be checked are read: a column equal to a scalar or `null`, `{ eq }`, `{ inq }`\n * (or `in`), an array, `and` of those, and an `or` whose branches all constrain the same column. Anything\n * else - an `or` over several columns, ranges, `like`, a nested path - makes\n * the scope unverifiable, and the write is refused with its own message instead of being skipped.\n */\nexport class ScopeWriteGuard {\n static extractConstraints(opts: { where: TWhere }): TExtraction {\n const constraints: TConstraints = new Map();\n const reason = ScopeWriteGuard.collect({\n where: opts.where as Record<string, unknown>,\n constraints,\n });\n\n return reason === undefined\n ? { isVerifiable: true, constraints }\n : { isVerifiable: false, reason };\n }\n\n /** Adds the where's constraints to `constraints`; returns the reason it cannot be verified, if any. */\n private static collect(opts: {\n where: Record<string, unknown>;\n constraints: TConstraints;\n }): string | undefined {\n const { where, constraints } = opts;\n\n for (const [key, value] of Object.entries(where)) {\n if (key === 'and') {\n if (!Array.isArray(value)) {\n return \"'and' is not a list\";\n }\n\n for (const part of value) {\n const reason = ScopeWriteGuard.collect({\n where: part as Record<string, unknown>,\n constraints,\n });\n\n if (reason !== undefined) {\n return reason;\n }\n }\n\n continue;\n }\n\n if (key === 'or') {\n const union = ScopeWriteGuard.unionOfBranches({ branches: value });\n\n if (typeof union === 'string') {\n return union;\n }\n\n const existing = constraints.get(union.column);\n constraints.set(\n union.column,\n existing ? intersect({ left: existing, right: union.allowed }) : union.allowed,\n );\n continue;\n }\n\n if (key.includes('.')) {\n return `the nested path '${key}' cannot be checked on a write`;\n }\n\n const allowed = ScopeWriteGuard.allowedValues({ value });\n\n if (typeof allowed === 'string') {\n return `column '${key}': ${allowed}`;\n }\n\n const existing = constraints.get(key);\n constraints.set(key, existing ? intersect({ left: existing, right: allowed }) : allowed);\n }\n\n return undefined;\n }\n\n /**\n * An `or` is checkable only when every branch constrains the same single column with a scalar,\n * `null`, `eq`, `in` or `inq`: the allowed values are then the union of the branches. This is the\n * shared-rows scope, `{ or: [{ merchantId: { in: ids } }, { merchantId: null }] }`. Any other `or`\n * (several columns, ranges, nested `and` or `or`) cannot be checked.\n */\n private static unionOfBranches(opts: {\n branches: unknown;\n }): { column: string; allowed: Set<string | null> } | string {\n const { branches } = opts;\n\n if (!Array.isArray(branches) || branches.length === 0) {\n return \"'or' is not a list\";\n }\n\n let column: string | undefined;\n const allowed = new Set<string | null>();\n\n for (const branch of branches) {\n const entries = Object.entries((branch ?? {}) as Record<string, unknown>);\n\n if (entries.length !== 1) {\n return \"an 'or' branch with several conditions cannot be checked on a write\";\n }\n\n const [key, value] = entries[0];\n\n if (key === 'and' || key === 'or' || key.includes('.')) {\n return `an 'or' branch over '${key}' cannot be checked on a write`;\n }\n\n if (column !== undefined && column !== key) {\n return \"an 'or' over different columns cannot be checked on a write\";\n }\n\n column = key;\n const values = ScopeWriteGuard.allowedValues({ value });\n\n if (typeof values === 'string') {\n return `column '${key}': ${values}`;\n }\n\n values.forEach((entry) => allowed.add(entry));\n }\n\n return { column: column as string, allowed };\n }\n\n /** The values one column's condition allows, or a string naming why it cannot be checked. */\n private static allowedValues(opts: { value: unknown }): Set<string | null> | string {\n const { value } = opts;\n\n if (isScalar(value)) {\n return new Set([normalise(value)]);\n }\n\n if (Array.isArray(value)) {\n return value.every(isScalar)\n ? new Set(value.map(normalise))\n : 'a list with a non-scalar entry';\n }\n\n if (typeof value !== 'object' || value === undefined) {\n return 'an unsupported condition';\n }\n\n const operators = Object.keys(value as object);\n\n if (operators.length !== 1) {\n return `a condition with ${operators.length} operators cannot be checked on a write`;\n }\n\n const [operator] = operators;\n const operand = (value as Record<string, unknown>)[operator];\n\n if (operator === QueryOperators.EQ && isScalar(operand)) {\n return new Set([normalise(operand)]);\n }\n\n if (\n (operator === QueryOperators.INQ || operator === QueryOperators.IN) &&\n Array.isArray(operand)\n ) {\n return operand.every(isScalar)\n ? new Set(operand.map(normalise))\n : 'a list with a non-scalar entry';\n }\n\n return `the operator '${operator}' cannot be checked on a write`;\n }\n\n /**\n * The scope as a MUTATION `where` (update, delete, soft delete, restore). A scope with a `null`\n * branch - `{ or: [{ merchantId: { in: ids } }, { merchantId: null }] }` - lets the caller READ the\n * shared rows. Changing or deleting one is the same permission as creating one, `write.sharedRows`,\n * so without it the `null` branch is removed and only the caller's own rows match. With\n * `sharedRows` the scope is returned as it is.\n *\n * Only the shapes the write guard can read are narrowed. Any other shape cannot be shown to exclude\n * the shared rows, so the mutation is refused, as an update with a payload already is.\n */\n static mutationWhere(opts: {\n settings: TModelAccessSettings;\n model: string;\n operation: TScopeOperation;\n scopeWhere: TWhere;\n }): TWhere {\n const { settings, model, operation, scopeWhere } = opts;\n\n ScopeWriteGuard.assertWrite({ model, operation });\n\n // Checked with `sharedRows` too: it lets the null branch through, not a shape the guard cannot read.\n const narrowed = ScopeWriteGuard.withoutShared({ where: scopeWhere });\n\n if (narrowed.kind === 'unverifiable') {\n throw ScopeWriteGuard.denied({\n model,\n operation,\n detail: `the resolved scope cannot be verified on a write | ${narrowed.reason}`,\n });\n }\n\n if (settings.write?.sharedRows === true) {\n return scopeWhere;\n }\n\n return narrowed.kind === 'none' ? ScopeFilterDenial.where() : narrowed.where;\n }\n\n /** `where` with every `null` the scope allows removed; `none` when nothing but `null` was allowed. */\n private static withoutShared(opts: { where: TWhere }): TNarrowed {\n const result: TWhere = {};\n\n for (const [key, value] of Object.entries(opts.where)) {\n if (key === 'and' || key === 'or') {\n if (!Array.isArray(value) || (key === 'or' && value.length === 0)) {\n return { kind: 'unverifiable', reason: `'${key}' is not a list` };\n }\n\n // An 'or' is read only when every branch constrains the same column, as the guard reads it: a branch over another column\n // could match a shared row without a null in sight.\n if (key === 'or') {\n const union = ScopeWriteGuard.unionOfBranches({ branches: value });\n\n if (typeof union === 'string') {\n return { kind: 'unverifiable', reason: union };\n }\n }\n\n const kept: TWhere[] = [];\n\n for (const part of value) {\n const narrowed = ScopeWriteGuard.withoutShared({\n where: RecordUtility.isPlainRecord(part) ? part : {},\n });\n\n if (narrowed.kind === 'unverifiable') {\n return narrowed;\n }\n\n if (narrowed.kind === 'none') {\n // One impossible 'and' part makes the whole 'and' impossible; an impossible 'or' branch just drops out.\n if (key === 'and') {\n return narrowed;\n }\n\n continue;\n }\n\n kept.push(narrowed.where);\n }\n\n if (key === 'or' && kept.length === 0) {\n return { kind: 'none' };\n }\n\n result[key] = kept;\n continue;\n }\n\n if (key.includes('.')) {\n return {\n kind: 'unverifiable',\n reason: `the nested path '${key}' cannot be checked on a write`,\n };\n }\n\n const narrowed = ScopeWriteGuard.conditionWithoutNull({ value });\n\n if (narrowed.kind !== 'condition') {\n return narrowed.kind === 'none'\n ? { kind: 'none' }\n : { kind: 'unverifiable', reason: `column '${key}': ${narrowed.reason}` };\n }\n\n result[key] = narrowed.value;\n }\n\n return { kind: 'where', where: result };\n }\n\n /** One column's condition without its `null` values, reading the same shapes `allowedValues` reads. */\n private static conditionWithoutNull(opts: {\n value: unknown;\n }):\n | { kind: 'condition'; value: unknown }\n | { kind: 'none' }\n | { kind: 'unverifiable'; reason: string } {\n const { value } = opts;\n\n const list = (entries: unknown[]) => {\n if (!entries.every(isScalar)) {\n return { kind: 'unverifiable' as const, reason: 'a list with a non-scalar entry' };\n }\n\n const kept = entries.filter((entry) => entry !== null);\n\n return kept.length === 0\n ? { kind: 'none' as const }\n : { kind: 'condition' as const, value: kept };\n };\n\n if (isScalar(value)) {\n return value === null ? { kind: 'none' } : { kind: 'condition', value };\n }\n\n if (Array.isArray(value)) {\n return list(value);\n }\n\n if (!RecordUtility.isPlainRecord(value)) {\n return { kind: 'unverifiable', reason: 'an unsupported condition' };\n }\n\n const operators = Object.keys(value);\n\n if (operators.length !== 1) {\n return {\n kind: 'unverifiable',\n reason: `a condition with ${operators.length} operators cannot be checked on a write`,\n };\n }\n\n const [operator] = operators;\n const operand = value[operator];\n\n if (operator === QueryOperators.EQ && isScalar(operand)) {\n return operand === null ? { kind: 'none' } : { kind: 'condition', value };\n }\n\n if (\n (operator === QueryOperators.INQ || operator === QueryOperators.IN) &&\n Array.isArray(operand)\n ) {\n const narrowed = list(operand);\n\n return narrowed.kind === 'condition'\n ? { kind: 'condition', value: { [operator]: narrowed.value } }\n : narrowed;\n }\n\n return {\n kind: 'unverifiable',\n reason: `the operator '${operator}' cannot be checked on a write`,\n };\n }\n\n /**\n * Holds `rows` to the scope `settings.resolve()` returns now. Returns the rows to write: the same\n * objects when nothing changes, copies with the scope columns filled in for `assign`. Throws, and\n * so writes nothing, when any row is outside the scope.\n */\n static apply<Row extends Record<string, unknown>>(opts: {\n settings: IModelAccessSettings;\n model: string;\n rows: Row[];\n operation: TScopeOperation;\n }): Row[] {\n const { settings, model, rows, operation } = opts;\n\n ScopeWriteGuard.assertWrite({ model, operation });\n\n const scope = settings.resolve({ operation });\n\n if (scope === ScopeFilters.UNRESTRICTED) {\n return rows;\n }\n\n if (scope === null || scope === undefined) {\n // An update is already confined by the scoped `where`, which under `deny` matches no row; the\n // guard adds nothing there. A create has no such `where`, so an unresolved scope refuses it.\n if (\n settings.onMissing === ScopeFilterMissingBehaviors.ALLOW ||\n operation !== ScopeOperations.CREATE\n ) {\n return rows;\n }\n\n throw ScopeWriteGuard.denied({\n model,\n operation,\n detail: 'no scope could be resolved for this caller',\n });\n }\n\n const extraction = ScopeWriteGuard.extractConstraints({ where: scope });\n\n if (!extraction.isVerifiable) {\n throw ScopeWriteGuard.denied({\n model,\n operation,\n detail: `the resolved scope cannot be verified on a write | ${extraction.reason}`,\n });\n }\n\n const { constraints } = extraction;\n const declared = settings.columns;\n\n if (declared) {\n const undeclared = [...constraints.keys()].find((column) => !declared.includes(column));\n\n if (undeclared !== undefined) {\n throw ScopeWriteGuard.denied({\n model,\n operation,\n detail: `the resolved scope constrains column '${undeclared}', which access.columns does not declare`,\n });\n }\n }\n\n const isAssign =\n settings.write?.mode === ScopeWriteGuards.ASSIGN && operation === ScopeOperations.CREATE;\n const sharedRows = settings.write?.sharedRows === true;\n\n return rows.map((row) => {\n let result = row;\n\n for (const [column, allowed] of constraints) {\n const value = (row as Record<string, unknown>)[column];\n\n if (value === undefined) {\n if (operation !== ScopeOperations.CREATE) {\n continue;\n }\n\n // `assign` first: stamping gives the row an owner, which is safer than leaving it shared.\n const only = allowed.size === 1 ? [...allowed][0] : undefined;\n\n if (isAssign && only !== undefined && only !== null) {\n result = { ...result, [column]: only };\n continue;\n }\n\n // Absent means the database default, usually `null`, so it is held to the `null` rule.\n if (sharedRows) {\n continue;\n }\n\n throw ScopeWriteGuard.denied({\n model,\n operation,\n column,\n detail: 'the scope column is missing',\n });\n }\n\n const normalised = isScalar(value) ? normalise(value) : undefined;\n // A `null` branch in the scope lets this caller READ shared rows. Writing one (or moving a\n // row into the shared set) is a separate permission: only `sharedRows` grants it.\n const isOutside = normalised === null ? !sharedRows : !allowed.has(normalised as string);\n\n if (normalised === undefined || isOutside) {\n throw ScopeWriteGuard.denied({\n model,\n operation,\n column,\n detail: 'the value is outside the resolved scope',\n });\n }\n }\n\n return result;\n });\n }\n\n /**\n * The write guard runs for a write only. A READ reaching it is a bug in the caller, not a request,\n * so it throws a plain error rather than a refusal the caller could map to a status.\n */\n private static assertWrite(opts: { model: string; operation: TScopeOperation }): void {\n const { model, operation } = opts;\n\n if (ScopeOperations.includes({ group: ScopeOperations.WRITE, operation })) {\n return;\n }\n\n throw getError({\n message: `[ScopeWriteGuard] the write guard runs for a write operation only | entity: ${model} | operation: ${operation}`,\n });\n }\n\n /**\n * A write to a `through` model named no parent, a parent that does not exist, or one outside the caller's scope. One\n * message for all three, so a foreign parent's existence does not leak.\n */\n static parentDenied(opts: { model: string; operation: TScopeOperation; column: string }) {\n return ScopeWriteGuard.denied({\n ...opts,\n detail: \"the parent is missing or outside the caller's scope\",\n });\n }\n\n /** Names the model and the column, never a value: the caller may be a request. */\n private static denied(opts: {\n model: string;\n operation: TScopeOperation;\n column?: string;\n detail: string;\n }) {\n const { model, operation, column, detail } = opts;\n\n return getError({\n statusCode: WRITE_DENIED_STATUS,\n messageCode: RepositoryErrorCodes.SCOPE_WRITE_DENIED,\n message: [\n `[${operation}] write refused by the access scope | entity: ${model}`,\n ...(column ? [`column: ${column}`] : []),\n detail,\n ].join(' | '),\n });\n }\n}\n"]}
|
|
@@ -200,7 +200,8 @@ export class RelationalBaseRepository extends AbstractRepository {
|
|
|
200
200
|
}
|
|
201
201
|
if (scopeWhere !== null && scopeWhere !== undefined) {
|
|
202
202
|
// A write reaches only the rows it may write: the shared (null) rows a read scope allows need `write.sharedRows`.
|
|
203
|
-
// A `through` scope is one foreign key set,
|
|
203
|
+
// A `through` scope is one foreign key set, but the parent's scope inside it can still carry a null branch: that is
|
|
204
|
+
// narrowed on the hop (`resolveThrough`), so this level has nothing left to narrow.
|
|
204
205
|
const effectiveWhere = mutation === undefined || scopeFilterSettings.through
|
|
205
206
|
? scopeWhere
|
|
206
207
|
: ScopeWriteGuard.mutationWhere({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../../../src/relational/core/repositories/core/base.ts"],"names":[],"mappings":"AAsBA,OAAO,EACL,kBAAkB,EAClB,aAAa,EACb,2BAA2B,EAC3B,YAAY,EACZ,eAAe,GAChB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,uBAAuB,EAAE,MAAM,sCAAsC,CAAC;AAC/E,OAAO,EAAE,oBAAoB,EAAE,MAAM,qDAAqD,CAAC;AAQ3F,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,GAAG,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAS5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAE9D,iTAAiT;AACjT,MAAM,OAAgB,wBAOpB,SAAQ,kBAA2D;IAGnE;;;;;;OAMG;IACO,SAAS,CAAC,IAA8B;QAChD,OAAO,EAAE,EAAE,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;IACzB,CAAC;IAQD,YACE,UAAwB,EACxB,IAIC;QAED,KAAK,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;QAd1B,yFAAyF;QACjF,uBAAkB,GAAuB,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,CAAC;QAED,OAAO,IAAI,CAAC,SAAS,CAAI,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;IAC/C,CAAC;CACF","sourcesContent":["import type {\n IdType,\n IExtraOptions,\n IPersistableRepository,\n IModelAccessThroughSettings,\n TModelAccessSettings,\n ITransaction,\n TCount,\n TByIdFilter,\n TDataRange,\n TDrizzleQueryOptions,\n TFields,\n TFilter,\n TFindOneOptions,\n TFindOptions,\n TFindRangeOptions,\n TLockOptions,\n TRepositoryOperationScope,\n TRow,\n TScopeOperation,\n TWhere,\n} from '@venizia/ignis-kernel';\nimport {\n AbstractRepository,\n LockStrengths,\n ScopeFilterMissingBehaviors,\n ScopeFilters,\n ScopeOperations,\n} from '@venizia/ignis-kernel';\n// Deep import, not the `@/relational/core/datasources` barrel: the barrel pulls the datasource classes, which import the engine branch's dialect and executor - an init cycle back into this tier.\nimport type { IRelationalDataSource } from '@/relational/core/datasources/common';\nimport { isRelationalTransaction } from '@/relational/core/datasources/common';\nimport { TransactionLifecycle } from '@/relational/core/datasources/transaction-lifecycle';\nimport type {\n BaseRelationalEntity,\n TTableInsert,\n TTableObject,\n TTableSchemaWithId,\n} from '@/relational/core/models';\nimport type { TClass, TNullable } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { and, getTableColumns, inArray } from 'drizzle-orm';\nimport type {\n IRelationalExtraOptions,\n IRelationalQueryDialect,\n IRelationalQueryExecutor,\n TRelationalConnectorOf,\n TRelationalTransactionOf,\n TRelationalTransactionOptionsOf,\n} from '../common';\nimport { ScopeFilterDenial } from '../common';\nimport { ScopeWriteGuard } from '../common/scope-write-guard';\n\n/** Relational implementation of `AbstractRepository`: adds the query dialect + hidden-column exclusion on top of the neutral base, and reaches the database only through `IRelationalQueryExecutor`. Both engine-facing parameters default to the neutral SQL contracts; an engine binds them by subclassing. */\nexport abstract class RelationalBaseRepository<\n EntitySchema extends TTableSchemaWithId = TTableSchemaWithId,\n DataObject extends TTableObject<EntitySchema> = TTableObject<EntitySchema>,\n PersistObject extends TTableInsert<EntitySchema> = TTableInsert<EntitySchema>,\n ExtraOptions extends IExtraOptions = IRelationalExtraOptions,\n TDataSource extends IRelationalDataSource = IRelationalDataSource,\n>\n extends AbstractRepository<DataObject, PersistObject, ExtraOptions>\n implements IPersistableRepository<DataObject, PersistObject, ExtraOptions>\n{\n /**\n * The `Pick` return type is load-bearing, not decoration. `TWhere<DataObject>` is a homomorphic\n * mapped type over an unresolved type parameter, and TypeScript cannot check a one-key literal\n * against it - `{ id }` fails even though `id` is a real key. `Pick<..., 'id'>` resolves that one\n * key, and the result still assigns to `TWhere<DataObject>` because every key there is optional.\n * Without it every `*ById` method needs a cast, which would hide a genuinely wrong id type.\n */\n protected whereById(opts: { id: DataObject['id'] }): Pick<TWhere<DataObject>, 'id'> {\n return { id: opts.id };\n }\n\n /** Memoized Set view of the base's `hiddenFields` array - built once on first access. */\n private _hiddenPropertySet: Set<string> | null = null;\n\n /** Memoized Drizzle column-selection map derived from hidden fields. `null` = not yet computed; `undefined` = computed, no hidden fields. */\n private _visibleColumns: Record<string, unknown> | null | undefined = null;\n\n constructor(\n dataSource?: TDataSource,\n opts?: {\n scope?: string;\n entityClass?: TClass<BaseRelationalEntity<EntitySchema>>;\n operationScope?: TRepositoryOperationScope;\n },\n ) {\n super(dataSource, opts);\n }\n\n override get dataSource(): TDataSource {\n return super.dataSource as TDataSource;\n }\n\n override set dataSource(value: TDataSource) {\n super.dataSource = value;\n }\n\n override get entity(): BaseRelationalEntity<EntitySchema> {\n return super.entity as BaseRelationalEntity<EntitySchema>;\n }\n\n override set entity(value: BaseRelationalEntity<EntitySchema>) {\n super.entity = value;\n }\n\n get queryDialect(): IRelationalQueryDialect {\n return this.dataSource.getQueryDialect();\n }\n\n /** Every Drizzle call the repository tier makes goes through this port, supplied by the engine branch via the datasource. */\n protected get queryExecutor(): IRelationalQueryExecutor<TRelationalConnectorOf<TDataSource>> {\n return this.dataSource.getQueryExecutor() as IRelationalQueryExecutor<\n TRelationalConnectorOf<TDataSource>\n >;\n }\n\n get connector(): TRelationalConnectorOf<TDataSource> {\n return this.dataSource.getConnector() as TRelationalConnectorOf<TDataSource>;\n }\n\n override setDataSource(opts: { dataSource: TDataSource }): void {\n super.setDataSource(opts);\n }\n\n getEntitySchema(): EntitySchema {\n return this.entity.schema;\n }\n\n /** Hidden fields as a memoized Set, derived from the base's class-keyed `hiddenFields` array. */\n getHiddenProperties(): Set<string> {\n this._hiddenPropertySet ??= new Set(this.hiddenFields);\n\n return this._hiddenPropertySet;\n }\n\n hasHiddenProperties(): boolean {\n return this.getHiddenProperties().size > 0;\n }\n\n /** Drizzle select/returning column map excluding hidden properties. Undefined if none hidden. Memoized. */\n getVisibleProperties(): Record<string, any> | undefined {\n if (this._visibleColumns !== null) {\n return this._visibleColumns;\n }\n\n const hiddenProps = this.getHiddenProperties();\n\n if (hiddenProps.size === 0) {\n this._visibleColumns = undefined;\n\n return undefined;\n }\n\n const columns = getTableColumns(this.entity.schema);\n const visibleProperties: Record<string, any> = {};\n\n for (const key in columns) {\n if (!hiddenProps.has(key)) {\n visibleProperties[key] = columns[key];\n }\n }\n\n this._visibleColumns = visibleProperties;\n\n return this._visibleColumns;\n }\n\n getDefaultFilter(): TFilter | undefined {\n return this.modelSettings?.query?.filter;\n }\n\n getDefaultLimit(): number | undefined {\n return this.defaultLimit;\n }\n\n hasDefaultFilter(): boolean {\n const defaultFilter = this.getDefaultFilter();\n\n return defaultFilter !== undefined && Object.keys(defaultFilter).length > 0;\n }\n\n /**\n * The model's `access` settings. Same override seam as `getDefaultFilter()` - a repository with no\n * resolvable `@model` entity (a synthetic test double, a hand-built stub) overrides this to avoid\n * touching `modelSettings`/`entity` at all.\n */\n getAccessSettings(): TModelAccessSettings | undefined {\n return this.modelSettings?.access;\n }\n\n /**\n * Holds written rows to the resolved row scope (`access.write`): refuses a row outside\n * it, and for `assign` returns copies with the scope columns filled in. Nothing is written when it\n * throws. Like the read scope, it is not skippable by `shouldSkipDefaultFilter`; a caller that is\n * trusted to write across scopes resolves to `ScopeFilters.UNRESTRICTED`.\n */\n protected async guardScopedWrite<Row extends Record<string, unknown>>(opts: {\n rows: Row[];\n operation: TScopeOperation;\n transaction?: ITransaction;\n }): Promise<Row[]> {\n const settings = this.getAccessSettings();\n\n if (!settings) {\n return opts.rows;\n }\n\n if (settings.through) {\n await this.assertParentsInScope({ ...opts, settings });\n\n return opts.rows;\n }\n\n return ScopeWriteGuard.apply({\n settings,\n model: this.entity.name,\n rows: opts.rows,\n operation: opts.operation,\n });\n }\n\n /**\n * A write to a model scoped through its parent: every parent key the rows name must be one the parent's own scope\n * allows for this operation. One query for the batch, read in the write's transaction (with `FOR SHARE` where the\n * engine can lock a row, so a parent that moves tenant after the check cannot be missed). A key that is null, absent,\n * missing from the parent table or outside the scope is the same refusal. An update names a key only to move the\n * row, so a payload without it checks nothing.\n */\n protected async assertParentsInScope(opts: {\n settings: IModelAccessThroughSettings;\n rows: Array<Record<string, unknown>>;\n operation: TScopeOperation;\n transaction?: ITransaction;\n }): Promise<void> {\n const { settings, operation, transaction } = opts;\n const { link, scope } = this.queryDialect.resolveThrough({\n settings,\n schema: this.entity.schema,\n operation,\n });\n const property = link.childProperty;\n const named =\n operation === ScopeOperations.CREATE ? opts.rows : opts.rows.filter((row) => property in row);\n\n if (named.length === 0) {\n return;\n }\n\n const denied = ScopeWriteGuard.parentDenied({\n model: this.entity.name,\n operation,\n column: property,\n });\n const keys = [...new Set(named.map((row) => row[property]))];\n const isUnresolved = scope === null || scope === undefined;\n\n if (keys.some((key) => key === null || key === undefined)) {\n throw denied;\n }\n\n // A parent that resolves no scope always denies its child: there is no onMissing to open it.\n if (isUnresolved) {\n throw denied;\n }\n\n const parentScope =\n scope === ScopeFilters.UNRESTRICTED\n ? undefined\n : this.queryDialect.toParentWhere({ link, scope });\n const found = await this.queryExecutor.select<{ key: unknown }>({\n connector: this.resolveConnector({ transaction }),\n table: link.parentSchema,\n columns: { key: link.parentColumn },\n where: and(inArray(link.parentColumn, keys), parentScope),\n lock: this.queryExecutor.supportsRowLock ? { strength: LockStrengths.SHARE } : undefined,\n });\n\n // Distinct keys, not rows: a parent column that is not unique can return two rows for one key and hide a missing one.\n if (new Set(found.map((row) => row.key)).size !== keys.length) {\n throw denied;\n }\n }\n\n /**\n * Row scope from `@model` settings.access - AND-composed like a default filter, but never\n * skippable via `shouldSkipDefaultFilter`: that flag serves `restore()`'s deliberate reach past\n * soft-delete, which must not also reach past tenant/ownership scoping.\n *\n * `dangerouslySkipScopeFilter` is framework-internal only, never part of `IExtraOptions` and never\n * wire-reachable: it exists so a filter this repository already scoped (find()'s own recursive\n * call) is not scoped a second time, and for explicitly-unscoped administrative code written and\n * reviewed at the repository - never inferable from a request.\n */\n protected applyScopeFilter<DO = any>(opts: {\n userFilter?: TFilter<DO>;\n dangerouslySkipScopeFilter?: boolean;\n mutation?: TScopeOperation;\n }): TFilter<DO> {\n const { userFilter, dangerouslySkipScopeFilter, mutation } = opts;\n\n if (dangerouslySkipScopeFilter) {\n return userFilter ?? {};\n }\n\n const scopeFilterSettings = this.getAccessSettings();\n\n if (!scopeFilterSettings) {\n return userFilter ?? {};\n }\n\n const scopeWhere = this.queryDialect.resolveAccessScope({\n settings: scopeFilterSettings,\n schema: this.entity.schema,\n operation: mutation ?? ScopeOperations.READ,\n });\n\n // Checked by exact symbol identity, before the null/undefined branch below: only this literal\n // value can skip scoping. A resolver that forgets a `return` on some branch produces\n // `undefined`, which is NOT this symbol and falls through to `onMissing` (deny by default).\n if (scopeWhere === ScopeFilters.UNRESTRICTED) {\n return userFilter ?? {};\n }\n\n if (scopeWhere !== null && scopeWhere !== undefined) {\n // A write reaches only the rows it may write: the shared (null) rows a read scope allows need `write.sharedRows`.\n // A `through` scope is one foreign key set, with no null branch for `sharedRows` to open, so it needs no narrowing.\n const effectiveWhere =\n mutation === undefined || scopeFilterSettings.through\n ? scopeWhere\n : ScopeWriteGuard.mutationWhere({\n settings: scopeFilterSettings,\n model: this.entity.name,\n operation: mutation,\n scopeWhere,\n });\n\n return this.queryDialect.mergeFilter({\n defaultFilter: { where: effectiveWhere },\n userFilter,\n });\n }\n\n if (scopeFilterSettings.onMissing === ScopeFilterMissingBehaviors.ALLOW) {\n return userFilter ?? {};\n }\n\n // 'deny' (default): an unresolved scope means the framework does not know what this caller may\n // see, and the safe reading of \"I do not know\" is \"nothing\" - never \"everything\".\n return this.queryDialect.mergeFilter({\n defaultFilter: { where: ScopeFilterDenial.where<DO>() },\n userFilter,\n });\n }\n\n /** Merges default filter with user filter. Skippable via shouldSkipDefaultFilter - the row scope from applyScopeFilter is not. */\n applyDefaultFilter<DO = any>(opts: {\n userFilter?: TFilter<DO>;\n shouldSkipDefaultFilter?: boolean;\n dangerouslySkipScopeFilter?: boolean;\n /** The name of the write (`update`, `delete`) when the filter selects rows to change: the row scope then leaves out the shared rows unless `write.sharedRows`. */\n mutation?: TScopeOperation;\n }): TFilter<DO> {\n const { userFilter, shouldSkipDefaultFilter, dangerouslySkipScopeFilter, mutation } = opts;\n\n const scopedFilter = this.applyScopeFilter<DO>({\n userFilter,\n dangerouslySkipScopeFilter,\n mutation,\n });\n\n if (shouldSkipDefaultFilter) {\n return scopedFilter;\n }\n\n const defaultFilter = this.getDefaultFilter();\n\n if (!defaultFilter) {\n return scopedFilter;\n }\n\n return this.queryDialect.mergeFilter({ defaultFilter, userFilter: scopedFilter });\n }\n\n async beginTransaction(\n opts?: TRelationalTransactionOptionsOf<TDataSource>,\n ): Promise<TRelationalTransactionOf<TDataSource>> {\n return this.dataSource.beginTransaction(opts) as Promise<TRelationalTransactionOf<TDataSource>>;\n }\n\n /**\n * Runs `execute` inside a transaction. Given a `transaction`, joins it: its owner commits or rolls\n * back, so this never does. Given none, owns one: begins it, commits when `execute` resolves, and\n * rolls back when `execute` or the commit throws - rethrowing the original error either way. An\n * owned transaction that `execute` already ended is never ended a second time.\n */\n async runInTransaction<ResultType>(opts: {\n transaction?: TRelationalTransactionOf<TDataSource>;\n transactionOptions?: TRelationalTransactionOptionsOf<TDataSource>;\n execute: (opts: { transaction: TRelationalTransactionOf<TDataSource> }) => Promise<ResultType>;\n }): Promise<ResultType> {\n const { transaction, transactionOptions, execute } = opts;\n\n if (transaction) {\n if (!transaction.isActive) {\n throw getError({\n message: `[${this.constructor.name}][runInTransaction] Transaction is no longer active`,\n });\n }\n\n if (transactionOptions) {\n this.logger\n .for('runInTransaction')\n .debug('Joined transaction | transactionOptions ignored: %j', transactionOptions);\n }\n\n return execute({ transaction });\n }\n\n const ownedTransaction = await this.beginTransaction(transactionOptions);\n\n let result: ResultType;\n\n try {\n const result2 = await execute({ transaction: ownedTransaction });\n result = result2;\n } catch (error) {\n if (ownedTransaction.isActive) {\n await this.rollbackOwnedTransaction({ transaction: ownedTransaction });\n }\n\n throw error;\n }\n\n if (!ownedTransaction.isActive) {\n return this.resolveEndedByExecute({ transaction: ownedTransaction, result });\n }\n\n try {\n await ownedTransaction.commit();\n } catch (error) {\n await this.rollbackOwnedTransaction({ transaction: ownedTransaction });\n throw error;\n }\n\n return result;\n }\n\n /** `execute` resolved after ending the owned transaction itself: its work stands only if it committed. */\n private resolveEndedByExecute<ResultType>(opts: {\n transaction: ITransaction;\n result: ResultType;\n }): ResultType {\n const { transaction, result } = opts;\n\n if (TransactionLifecycle.isCommitted({ transaction })) {\n this.logger\n .for('runInTransaction')\n .warn('execute committed the owned transaction itself | Skipped the commit');\n\n return result;\n }\n\n throw getError({\n message: `[${this.constructor.name}][runInTransaction] execute ended the owned transaction before it could be committed`,\n });\n }\n\n /** A rollback failure is only logged: the caller needs the error that made the rollback necessary. */\n private async rollbackOwnedTransaction(opts: { transaction: ITransaction }): Promise<void> {\n try {\n await opts.transaction.rollback();\n } catch (rollbackError) {\n this.logger\n .for('runInTransaction')\n .error(\n 'Rollback failed, rethrowing the original error | Rollback error: %s',\n rollbackError,\n );\n }\n }\n\n /** Builds Drizzle query options from a filter, excluding hidden properties. */\n buildQuery(opts: { filter: TFilter<DataObject> }): TDrizzleQueryOptions {\n const result = this.queryDialect.build({\n tableName: this.entity.name,\n schema: this.entity.schema,\n // The dialect reads the filter against the table object; `DataObject` is the same row.\n filter: opts.filter as TFilter,\n });\n\n if (!this.hasHiddenProperties()) {\n return result;\n }\n\n const hiddenProps = this.getHiddenProperties();\n\n if (result.columns) {\n result.columns = this.omitHiddenColumns({ columns: result.columns, hiddenProps });\n\n return result;\n }\n\n const visibleProps = this.getVisibleProperties();\n\n if (visibleProps) {\n const filteredColumns: Record<string, boolean> = {};\n\n for (const key in visibleProps) {\n filteredColumns[key] = true;\n }\n\n result.columns = filteredColumns;\n }\n\n return result;\n }\n\n /** Copy of a Drizzle column selection with hidden properties dropped. */\n private omitHiddenColumns(opts: {\n columns: Record<string, boolean>;\n hiddenProps: Set<string>;\n }): Record<string, boolean> {\n const { columns, hiddenProps } = opts;\n const filteredColumns: Record<string, boolean> = {};\n\n for (const key in columns) {\n if (hiddenProps.has(key)) {\n continue;\n }\n\n filteredColumns[key] = columns[key];\n }\n\n return filteredColumns;\n }\n\n /** Resolves the database connector, using the transaction's connector if provided. */\n protected resolveConnector(opts?: {\n transaction?: ITransaction;\n }): TRelationalConnectorOf<TDataSource> {\n const { transaction } = opts ?? {};\n\n if (!transaction) {\n return this.dataSource.getConnector() as TRelationalConnectorOf<TDataSource>;\n }\n\n if (!transaction.isActive) {\n throw getError({\n message: `[${this.constructor.name}][resolveConnector] Transaction is no longer active`,\n });\n }\n\n if (!isRelationalTransaction(transaction)) {\n throw getError({\n message: `[${this.constructor.name}][resolveConnector] Transaction is not a relational transaction`,\n });\n }\n\n return transaction.connector as TRelationalConnectorOf<TDataSource>;\n }\n\n /** Validates lock options: requires transaction, incompatible with Query API (include/fields). */\n protected validateLockOptions(opts: {\n lock?: TLockOptions;\n transaction?: ITransaction;\n usesQueryAPI?: boolean;\n }): void {\n if (!opts.lock) {\n return;\n }\n\n if (!opts.transaction) {\n throw getError({\n message: `[${this.constructor.name}][validateLockOptions] Row-level locking requires a transaction`,\n });\n }\n\n if (opts.usesQueryAPI) {\n throw getError({\n message: `[${this.constructor.name}][validateLockOptions] Row-level locking is incompatible with Query API`,\n });\n }\n }\n\n abstract override count(opts: {\n where: TWhere<DataObject>;\n options?: ExtraOptions;\n }): Promise<TCount>;\n\n abstract override existsWith(opts: {\n where: TWhere<DataObject>;\n options?: ExtraOptions;\n }): Promise<boolean>;\n\n abstract override find<\n R = unknown,\n const F extends TFields<DataObject> = TFields<DataObject>,\n >(opts: {\n filter: TFilter<DataObject, F>;\n options: TFindRangeOptions<ExtraOptions, TRow<DataObject, R, F>>;\n }): Promise<{ data: Array<TRow<DataObject, R, F>>; range: TDataRange }>;\n\n abstract override find<\n R = unknown,\n const F extends TFields<DataObject> = TFields<DataObject>,\n >(opts: {\n filter: TFilter<DataObject, F>;\n options?: TFindOptions<ExtraOptions, TRow<DataObject, R, F>>;\n }): Promise<Array<TRow<DataObject, R, F>>>;\n\n abstract override findOne<\n R = unknown,\n const F extends TFields<DataObject> = TFields<DataObject>,\n >(opts: {\n filter: TFilter<DataObject, F>;\n options?: TFindOneOptions<ExtraOptions, TRow<DataObject, R, F>>;\n }): Promise<TNullable<TRow<DataObject, R, F>>>;\n\n abstract override findById<\n R = unknown,\n const F extends TFields<DataObject> = TFields<DataObject>,\n >(opts: {\n id: IdType;\n filter?: TByIdFilter<DataObject, F>;\n options?: TFindOneOptions<ExtraOptions, TRow<DataObject, R, F>>;\n }): Promise<TNullable<TRow<DataObject, R, F>>>;\n\n abstract override create(opts: {\n data: PersistObject;\n options: ExtraOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract override create<R = DataObject>(opts: {\n data: PersistObject;\n options?: ExtraOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: R }>;\n\n abstract override createAll(opts: {\n data: Array<PersistObject>;\n options: ExtraOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract override createAll<R = DataObject>(opts: {\n data: Array<PersistObject>;\n options?: ExtraOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: Array<R> }>;\n\n abstract override updateById(opts: {\n id: IdType;\n data: Partial<PersistObject>;\n options: ExtraOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract override updateById<R = DataObject>(opts: {\n id: IdType;\n data: Partial<PersistObject>;\n options?: ExtraOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: R }>;\n\n abstract override updateAll(opts: {\n data: Partial<PersistObject>;\n where: TWhere<DataObject>;\n options: ExtraOptions & { shouldReturn: false; force?: boolean };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract override updateAll<R = DataObject>(opts: {\n data: Partial<PersistObject>;\n where: TWhere<DataObject>;\n options?: ExtraOptions & { shouldReturn?: true; force?: boolean };\n }): Promise<TCount & { data: Array<R> }>;\n\n // Re-declared, not inherited: the base alias is `Array<R> | null` to cover the search family, but SQL engines have RETURNING so this surface must stay exactly `Array<R>`.\n override updateBy(opts: {\n data: Partial<PersistObject>;\n where: TWhere<DataObject>;\n options: ExtraOptions & { shouldReturn: false; force?: boolean };\n }): Promise<TCount & { data: undefined | null }>;\n override updateBy<R = DataObject>(opts: {\n data: Partial<PersistObject>;\n where: TWhere<DataObject>;\n options?: ExtraOptions & { shouldReturn?: true; force?: boolean };\n }): Promise<TCount & { data: Array<R> }>;\n override updateBy<R = DataObject>(opts: {\n data: Partial<PersistObject>;\n where: TWhere<DataObject>;\n options?: ExtraOptions & { shouldReturn?: boolean; force?: boolean };\n }): Promise<TCount & { data: TNullable<Array<R>> }> {\n const { data, where, options } = opts;\n\n if (options?.shouldReturn === false) {\n return this.updateAll({ data, where, options: { ...options, shouldReturn: false } });\n }\n\n return this.updateAll<R>({ data, where, options });\n }\n\n abstract override deleteById(opts: {\n id: IdType;\n options: ExtraOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract override deleteById<R = DataObject>(opts: {\n id: IdType;\n options?: ExtraOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: R }>;\n\n abstract override deleteAll(opts: {\n where?: TWhere<DataObject>;\n options: ExtraOptions & { shouldReturn: false; force?: boolean };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract override deleteAll<R = DataObject>(opts: {\n where?: TWhere<DataObject>;\n options?: ExtraOptions & { shouldReturn?: true; force?: boolean };\n }): Promise<TCount & { data: Array<R> }>;\n\n // Same rationale as updateBy above: keep this alias surface at `Array<R>`.\n override deleteBy(opts: {\n where?: TWhere<DataObject>;\n options: ExtraOptions & { shouldReturn: false; force?: boolean };\n }): Promise<TCount & { data: undefined | null }>;\n override deleteBy<R = DataObject>(opts: {\n where?: TWhere<DataObject>;\n options?: ExtraOptions & { shouldReturn?: true; force?: boolean };\n }): Promise<TCount & { data: Array<R> }>;\n override deleteBy<R = DataObject>(opts: {\n where?: TWhere<DataObject>;\n options?: ExtraOptions & { shouldReturn?: boolean; force?: boolean };\n }): Promise<TCount & { data: TNullable<Array<R>> }> {\n const { where, options } = opts;\n\n if (options?.shouldReturn === false) {\n return this.deleteAll({ where, options: { ...options, shouldReturn: false } });\n }\n\n return this.deleteAll<R>({ where, options });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../../../src/relational/core/repositories/core/base.ts"],"names":[],"mappings":"AAsBA,OAAO,EACL,kBAAkB,EAClB,aAAa,EACb,2BAA2B,EAC3B,YAAY,EACZ,eAAe,GAChB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,uBAAuB,EAAE,MAAM,sCAAsC,CAAC;AAC/E,OAAO,EAAE,oBAAoB,EAAE,MAAM,qDAAqD,CAAC;AAQ3F,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,GAAG,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAS5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAA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E,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;IACrD,CAAC;IA+BQ,QAAQ,CAAiB,IAGjC;QACC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QAEhC,IAAI,OAAO,EAAE,YAAY,KAAK,KAAK,EAAE,CAAC;YACpC,OAAO,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;QACjF,CAAC;QAED,OAAO,IAAI,CAAC,SAAS,CAAI,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;IAC/C,CAAC;CACF","sourcesContent":["import type {\n IdType,\n IExtraOptions,\n IPersistableRepository,\n IModelAccessThroughSettings,\n TModelAccessSettings,\n ITransaction,\n TCount,\n TByIdFilter,\n TDataRange,\n TDrizzleQueryOptions,\n TFields,\n TFilter,\n TFindOneOptions,\n TFindOptions,\n TFindRangeOptions,\n TLockOptions,\n TRepositoryOperationScope,\n TRow,\n TScopeOperation,\n TWhere,\n} from '@venizia/ignis-kernel';\nimport {\n AbstractRepository,\n LockStrengths,\n ScopeFilterMissingBehaviors,\n ScopeFilters,\n ScopeOperations,\n} from '@venizia/ignis-kernel';\n// Deep import, not the `@/relational/core/datasources` barrel: the barrel pulls the datasource classes, which import the engine branch's dialect and executor - an init cycle back into this tier.\nimport type { IRelationalDataSource } from '@/relational/core/datasources/common';\nimport { isRelationalTransaction } from '@/relational/core/datasources/common';\nimport { TransactionLifecycle } from '@/relational/core/datasources/transaction-lifecycle';\nimport type {\n BaseRelationalEntity,\n TTableInsert,\n TTableObject,\n TTableSchemaWithId,\n} from '@/relational/core/models';\nimport type { TClass, TNullable } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { and, getTableColumns, inArray } from 'drizzle-orm';\nimport type {\n IRelationalExtraOptions,\n IRelationalQueryDialect,\n IRelationalQueryExecutor,\n TRelationalConnectorOf,\n TRelationalTransactionOf,\n TRelationalTransactionOptionsOf,\n} from '../common';\nimport { ScopeFilterDenial } from '../common';\nimport { ScopeWriteGuard } from '../common/scope-write-guard';\n\n/** Relational implementation of `AbstractRepository`: adds the query dialect + hidden-column exclusion on top of the neutral base, and reaches the database only through `IRelationalQueryExecutor`. Both engine-facing parameters default to the neutral SQL contracts; an engine binds them by subclassing. */\nexport abstract class RelationalBaseRepository<\n EntitySchema extends TTableSchemaWithId = TTableSchemaWithId,\n DataObject extends TTableObject<EntitySchema> = TTableObject<EntitySchema>,\n PersistObject extends TTableInsert<EntitySchema> = TTableInsert<EntitySchema>,\n ExtraOptions extends IExtraOptions = IRelationalExtraOptions,\n TDataSource extends IRelationalDataSource = IRelationalDataSource,\n>\n extends AbstractRepository<DataObject, PersistObject, ExtraOptions>\n implements IPersistableRepository<DataObject, PersistObject, ExtraOptions>\n{\n /**\n * The `Pick` return type is load-bearing, not decoration. `TWhere<DataObject>` is a homomorphic\n * mapped type over an unresolved type parameter, and TypeScript cannot check a one-key literal\n * against it - `{ id }` fails even though `id` is a real key. `Pick<..., 'id'>` resolves that one\n * key, and the result still assigns to `TWhere<DataObject>` because every key there is optional.\n * Without it every `*ById` method needs a cast, which would hide a genuinely wrong id type.\n */\n protected whereById(opts: { id: DataObject['id'] }): Pick<TWhere<DataObject>, 'id'> {\n return { id: opts.id };\n }\n\n /** Memoized Set view of the base's `hiddenFields` array - built once on first access. */\n private _hiddenPropertySet: Set<string> | null = null;\n\n /** Memoized Drizzle column-selection map derived from hidden fields. `null` = not yet computed; `undefined` = computed, no hidden fields. */\n private _visibleColumns: Record<string, unknown> | null | undefined = null;\n\n constructor(\n dataSource?: TDataSource,\n opts?: {\n scope?: string;\n entityClass?: TClass<BaseRelationalEntity<EntitySchema>>;\n operationScope?: TRepositoryOperationScope;\n },\n ) {\n super(dataSource, opts);\n }\n\n override get dataSource(): TDataSource {\n return super.dataSource as TDataSource;\n }\n\n override set dataSource(value: TDataSource) {\n super.dataSource = value;\n }\n\n override get entity(): BaseRelationalEntity<EntitySchema> {\n return super.entity as BaseRelationalEntity<EntitySchema>;\n }\n\n override set entity(value: BaseRelationalEntity<EntitySchema>) {\n super.entity = value;\n }\n\n get queryDialect(): IRelationalQueryDialect {\n return this.dataSource.getQueryDialect();\n }\n\n /** Every Drizzle call the repository tier makes goes through this port, supplied by the engine branch via the datasource. */\n protected get queryExecutor(): IRelationalQueryExecutor<TRelationalConnectorOf<TDataSource>> {\n return this.dataSource.getQueryExecutor() as IRelationalQueryExecutor<\n TRelationalConnectorOf<TDataSource>\n >;\n }\n\n get connector(): TRelationalConnectorOf<TDataSource> {\n return this.dataSource.getConnector() as TRelationalConnectorOf<TDataSource>;\n }\n\n override setDataSource(opts: { dataSource: TDataSource }): void {\n super.setDataSource(opts);\n }\n\n getEntitySchema(): EntitySchema {\n return this.entity.schema;\n }\n\n /** Hidden fields as a memoized Set, derived from the base's class-keyed `hiddenFields` array. */\n getHiddenProperties(): Set<string> {\n this._hiddenPropertySet ??= new Set(this.hiddenFields);\n\n return this._hiddenPropertySet;\n }\n\n hasHiddenProperties(): boolean {\n return this.getHiddenProperties().size > 0;\n }\n\n /** Drizzle select/returning column map excluding hidden properties. Undefined if none hidden. Memoized. */\n getVisibleProperties(): Record<string, any> | undefined {\n if (this._visibleColumns !== null) {\n return this._visibleColumns;\n }\n\n const hiddenProps = this.getHiddenProperties();\n\n if (hiddenProps.size === 0) {\n this._visibleColumns = undefined;\n\n return undefined;\n }\n\n const columns = getTableColumns(this.entity.schema);\n const visibleProperties: Record<string, any> = {};\n\n for (const key in columns) {\n if (!hiddenProps.has(key)) {\n visibleProperties[key] = columns[key];\n }\n }\n\n this._visibleColumns = visibleProperties;\n\n return this._visibleColumns;\n }\n\n getDefaultFilter(): TFilter | undefined {\n return this.modelSettings?.query?.filter;\n }\n\n getDefaultLimit(): number | undefined {\n return this.defaultLimit;\n }\n\n hasDefaultFilter(): boolean {\n const defaultFilter = this.getDefaultFilter();\n\n return defaultFilter !== undefined && Object.keys(defaultFilter).length > 0;\n }\n\n /**\n * The model's `access` settings. Same override seam as `getDefaultFilter()` - a repository with no\n * resolvable `@model` entity (a synthetic test double, a hand-built stub) overrides this to avoid\n * touching `modelSettings`/`entity` at all.\n */\n getAccessSettings(): TModelAccessSettings | undefined {\n return this.modelSettings?.access;\n }\n\n /**\n * Holds written rows to the resolved row scope (`access.write`): refuses a row outside\n * it, and for `assign` returns copies with the scope columns filled in. Nothing is written when it\n * throws. Like the read scope, it is not skippable by `shouldSkipDefaultFilter`; a caller that is\n * trusted to write across scopes resolves to `ScopeFilters.UNRESTRICTED`.\n */\n protected async guardScopedWrite<Row extends Record<string, unknown>>(opts: {\n rows: Row[];\n operation: TScopeOperation;\n transaction?: ITransaction;\n }): Promise<Row[]> {\n const settings = this.getAccessSettings();\n\n if (!settings) {\n return opts.rows;\n }\n\n if (settings.through) {\n await this.assertParentsInScope({ ...opts, settings });\n\n return opts.rows;\n }\n\n return ScopeWriteGuard.apply({\n settings,\n model: this.entity.name,\n rows: opts.rows,\n operation: opts.operation,\n });\n }\n\n /**\n * A write to a model scoped through its parent: every parent key the rows name must be one the parent's own scope\n * allows for this operation. One query for the batch, read in the write's transaction (with `FOR SHARE` where the\n * engine can lock a row, so a parent that moves tenant after the check cannot be missed). A key that is null, absent,\n * missing from the parent table or outside the scope is the same refusal. An update names a key only to move the\n * row, so a payload without it checks nothing.\n */\n protected async assertParentsInScope(opts: {\n settings: IModelAccessThroughSettings;\n rows: Array<Record<string, unknown>>;\n operation: TScopeOperation;\n transaction?: ITransaction;\n }): Promise<void> {\n const { settings, operation, transaction } = opts;\n const { link, scope } = this.queryDialect.resolveThrough({\n settings,\n schema: this.entity.schema,\n operation,\n });\n const property = link.childProperty;\n const named =\n operation === ScopeOperations.CREATE ? opts.rows : opts.rows.filter((row) => property in row);\n\n if (named.length === 0) {\n return;\n }\n\n const denied = ScopeWriteGuard.parentDenied({\n model: this.entity.name,\n operation,\n column: property,\n });\n const keys = [...new Set(named.map((row) => row[property]))];\n const isUnresolved = scope === null || scope === undefined;\n\n if (keys.some((key) => key === null || key === undefined)) {\n throw denied;\n }\n\n // A parent that resolves no scope always denies its child: there is no onMissing to open it.\n if (isUnresolved) {\n throw denied;\n }\n\n const parentScope =\n scope === ScopeFilters.UNRESTRICTED\n ? undefined\n : this.queryDialect.toParentWhere({ link, scope });\n const found = await this.queryExecutor.select<{ key: unknown }>({\n connector: this.resolveConnector({ transaction }),\n table: link.parentSchema,\n columns: { key: link.parentColumn },\n where: and(inArray(link.parentColumn, keys), parentScope),\n lock: this.queryExecutor.supportsRowLock ? { strength: LockStrengths.SHARE } : undefined,\n });\n\n // Distinct keys, not rows: a parent column that is not unique can return two rows for one key and hide a missing one.\n if (new Set(found.map((row) => row.key)).size !== keys.length) {\n throw denied;\n }\n }\n\n /**\n * Row scope from `@model` settings.access - AND-composed like a default filter, but never\n * skippable via `shouldSkipDefaultFilter`: that flag serves `restore()`'s deliberate reach past\n * soft-delete, which must not also reach past tenant/ownership scoping.\n *\n * `dangerouslySkipScopeFilter` is framework-internal only, never part of `IExtraOptions` and never\n * wire-reachable: it exists so a filter this repository already scoped (find()'s own recursive\n * call) is not scoped a second time, and for explicitly-unscoped administrative code written and\n * reviewed at the repository - never inferable from a request.\n */\n protected applyScopeFilter<DO = any>(opts: {\n userFilter?: TFilter<DO>;\n dangerouslySkipScopeFilter?: boolean;\n mutation?: TScopeOperation;\n }): TFilter<DO> {\n const { userFilter, dangerouslySkipScopeFilter, mutation } = opts;\n\n if (dangerouslySkipScopeFilter) {\n return userFilter ?? {};\n }\n\n const scopeFilterSettings = this.getAccessSettings();\n\n if (!scopeFilterSettings) {\n return userFilter ?? {};\n }\n\n const scopeWhere = this.queryDialect.resolveAccessScope({\n settings: scopeFilterSettings,\n schema: this.entity.schema,\n operation: mutation ?? ScopeOperations.READ,\n });\n\n // Checked by exact symbol identity, before the null/undefined branch below: only this literal\n // value can skip scoping. A resolver that forgets a `return` on some branch produces\n // `undefined`, which is NOT this symbol and falls through to `onMissing` (deny by default).\n if (scopeWhere === ScopeFilters.UNRESTRICTED) {\n return userFilter ?? {};\n }\n\n if (scopeWhere !== null && scopeWhere !== undefined) {\n // A write reaches only the rows it may write: the shared (null) rows a read scope allows need `write.sharedRows`.\n // A `through` scope is one foreign key set, but the parent's scope inside it can still carry a null branch: that is\n // narrowed on the hop (`resolveThrough`), so this level has nothing left to narrow.\n const effectiveWhere =\n mutation === undefined || scopeFilterSettings.through\n ? scopeWhere\n : ScopeWriteGuard.mutationWhere({\n settings: scopeFilterSettings,\n model: this.entity.name,\n operation: mutation,\n scopeWhere,\n });\n\n return this.queryDialect.mergeFilter({\n defaultFilter: { where: effectiveWhere },\n userFilter,\n });\n }\n\n if (scopeFilterSettings.onMissing === ScopeFilterMissingBehaviors.ALLOW) {\n return userFilter ?? {};\n }\n\n // 'deny' (default): an unresolved scope means the framework does not know what this caller may\n // see, and the safe reading of \"I do not know\" is \"nothing\" - never \"everything\".\n return this.queryDialect.mergeFilter({\n defaultFilter: { where: ScopeFilterDenial.where<DO>() },\n userFilter,\n });\n }\n\n /** Merges default filter with user filter. Skippable via shouldSkipDefaultFilter - the row scope from applyScopeFilter is not. */\n applyDefaultFilter<DO = any>(opts: {\n userFilter?: TFilter<DO>;\n shouldSkipDefaultFilter?: boolean;\n dangerouslySkipScopeFilter?: boolean;\n /** The name of the write (`update`, `delete`) when the filter selects rows to change: the row scope then leaves out the shared rows unless `write.sharedRows`. */\n mutation?: TScopeOperation;\n }): TFilter<DO> {\n const { userFilter, shouldSkipDefaultFilter, dangerouslySkipScopeFilter, mutation } = opts;\n\n const scopedFilter = this.applyScopeFilter<DO>({\n userFilter,\n dangerouslySkipScopeFilter,\n mutation,\n });\n\n if (shouldSkipDefaultFilter) {\n return scopedFilter;\n }\n\n const defaultFilter = this.getDefaultFilter();\n\n if (!defaultFilter) {\n return scopedFilter;\n }\n\n return this.queryDialect.mergeFilter({ defaultFilter, userFilter: scopedFilter });\n }\n\n async beginTransaction(\n opts?: TRelationalTransactionOptionsOf<TDataSource>,\n ): Promise<TRelationalTransactionOf<TDataSource>> {\n return this.dataSource.beginTransaction(opts) as Promise<TRelationalTransactionOf<TDataSource>>;\n }\n\n /**\n * Runs `execute` inside a transaction. Given a `transaction`, joins it: its owner commits or rolls\n * back, so this never does. Given none, owns one: begins it, commits when `execute` resolves, and\n * rolls back when `execute` or the commit throws - rethrowing the original error either way. An\n * owned transaction that `execute` already ended is never ended a second time.\n */\n async runInTransaction<ResultType>(opts: {\n transaction?: TRelationalTransactionOf<TDataSource>;\n transactionOptions?: TRelationalTransactionOptionsOf<TDataSource>;\n execute: (opts: { transaction: TRelationalTransactionOf<TDataSource> }) => Promise<ResultType>;\n }): Promise<ResultType> {\n const { transaction, transactionOptions, execute } = opts;\n\n if (transaction) {\n if (!transaction.isActive) {\n throw getError({\n message: `[${this.constructor.name}][runInTransaction] Transaction is no longer active`,\n });\n }\n\n if (transactionOptions) {\n this.logger\n .for('runInTransaction')\n .debug('Joined transaction | transactionOptions ignored: %j', transactionOptions);\n }\n\n return execute({ transaction });\n }\n\n const ownedTransaction = await this.beginTransaction(transactionOptions);\n\n let result: ResultType;\n\n try {\n const result2 = await execute({ transaction: ownedTransaction });\n result = result2;\n } catch (error) {\n if (ownedTransaction.isActive) {\n await this.rollbackOwnedTransaction({ transaction: ownedTransaction });\n }\n\n throw error;\n }\n\n if (!ownedTransaction.isActive) {\n return this.resolveEndedByExecute({ transaction: ownedTransaction, result });\n }\n\n try {\n await ownedTransaction.commit();\n } catch (error) {\n await this.rollbackOwnedTransaction({ transaction: ownedTransaction });\n throw error;\n }\n\n return result;\n }\n\n /** `execute` resolved after ending the owned transaction itself: its work stands only if it committed. */\n private resolveEndedByExecute<ResultType>(opts: {\n transaction: ITransaction;\n result: ResultType;\n }): ResultType {\n const { transaction, result } = opts;\n\n if (TransactionLifecycle.isCommitted({ transaction })) {\n this.logger\n .for('runInTransaction')\n .warn('execute committed the owned transaction itself | Skipped the commit');\n\n return result;\n }\n\n throw getError({\n message: `[${this.constructor.name}][runInTransaction] execute ended the owned transaction before it could be committed`,\n });\n }\n\n /** A rollback failure is only logged: the caller needs the error that made the rollback necessary. */\n private async rollbackOwnedTransaction(opts: { transaction: ITransaction }): Promise<void> {\n try {\n await opts.transaction.rollback();\n } catch (rollbackError) {\n this.logger\n .for('runInTransaction')\n .error(\n 'Rollback failed, rethrowing the original error | Rollback error: %s',\n rollbackError,\n );\n }\n }\n\n /** Builds Drizzle query options from a filter, excluding hidden properties. */\n buildQuery(opts: { filter: TFilter<DataObject> }): TDrizzleQueryOptions {\n const result = this.queryDialect.build({\n tableName: this.entity.name,\n schema: this.entity.schema,\n // The dialect reads the filter against the table object; `DataObject` is the same row.\n filter: opts.filter as TFilter,\n });\n\n if (!this.hasHiddenProperties()) {\n return result;\n }\n\n const hiddenProps = this.getHiddenProperties();\n\n if (result.columns) {\n result.columns = this.omitHiddenColumns({ columns: result.columns, hiddenProps });\n\n return result;\n }\n\n const visibleProps = this.getVisibleProperties();\n\n if (visibleProps) {\n const filteredColumns: Record<string, boolean> = {};\n\n for (const key in visibleProps) {\n filteredColumns[key] = true;\n }\n\n result.columns = filteredColumns;\n }\n\n return result;\n }\n\n /** Copy of a Drizzle column selection with hidden properties dropped. */\n private omitHiddenColumns(opts: {\n columns: Record<string, boolean>;\n hiddenProps: Set<string>;\n }): Record<string, boolean> {\n const { columns, hiddenProps } = opts;\n const filteredColumns: Record<string, boolean> = {};\n\n for (const key in columns) {\n if (hiddenProps.has(key)) {\n continue;\n }\n\n filteredColumns[key] = columns[key];\n }\n\n return filteredColumns;\n }\n\n /** Resolves the database connector, using the transaction's connector if provided. */\n protected resolveConnector(opts?: {\n transaction?: ITransaction;\n }): TRelationalConnectorOf<TDataSource> {\n const { transaction } = opts ?? {};\n\n if (!transaction) {\n return this.dataSource.getConnector() as TRelationalConnectorOf<TDataSource>;\n }\n\n if (!transaction.isActive) {\n throw getError({\n message: `[${this.constructor.name}][resolveConnector] Transaction is no longer active`,\n });\n }\n\n if (!isRelationalTransaction(transaction)) {\n throw getError({\n message: `[${this.constructor.name}][resolveConnector] Transaction is not a relational transaction`,\n });\n }\n\n return transaction.connector as TRelationalConnectorOf<TDataSource>;\n }\n\n /** Validates lock options: requires transaction, incompatible with Query API (include/fields). */\n protected validateLockOptions(opts: {\n lock?: TLockOptions;\n transaction?: ITransaction;\n usesQueryAPI?: boolean;\n }): void {\n if (!opts.lock) {\n return;\n }\n\n if (!opts.transaction) {\n throw getError({\n message: `[${this.constructor.name}][validateLockOptions] Row-level locking requires a transaction`,\n });\n }\n\n if (opts.usesQueryAPI) {\n throw getError({\n message: `[${this.constructor.name}][validateLockOptions] Row-level locking is incompatible with Query API`,\n });\n }\n }\n\n abstract override count(opts: {\n where: TWhere<DataObject>;\n options?: ExtraOptions;\n }): Promise<TCount>;\n\n abstract override existsWith(opts: {\n where: TWhere<DataObject>;\n options?: ExtraOptions;\n }): Promise<boolean>;\n\n abstract override find<\n R = unknown,\n const F extends TFields<DataObject> = TFields<DataObject>,\n >(opts: {\n filter: TFilter<DataObject, F>;\n options: TFindRangeOptions<ExtraOptions, TRow<DataObject, R, F>>;\n }): Promise<{ data: Array<TRow<DataObject, R, F>>; range: TDataRange }>;\n\n abstract override find<\n R = unknown,\n const F extends TFields<DataObject> = TFields<DataObject>,\n >(opts: {\n filter: TFilter<DataObject, F>;\n options?: TFindOptions<ExtraOptions, TRow<DataObject, R, F>>;\n }): Promise<Array<TRow<DataObject, R, F>>>;\n\n abstract override findOne<\n R = unknown,\n const F extends TFields<DataObject> = TFields<DataObject>,\n >(opts: {\n filter: TFilter<DataObject, F>;\n options?: TFindOneOptions<ExtraOptions, TRow<DataObject, R, F>>;\n }): Promise<TNullable<TRow<DataObject, R, F>>>;\n\n abstract override findById<\n R = unknown,\n const F extends TFields<DataObject> = TFields<DataObject>,\n >(opts: {\n id: IdType;\n filter?: TByIdFilter<DataObject, F>;\n options?: TFindOneOptions<ExtraOptions, TRow<DataObject, R, F>>;\n }): Promise<TNullable<TRow<DataObject, R, F>>>;\n\n abstract override create(opts: {\n data: PersistObject;\n options: ExtraOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract override create<R = DataObject>(opts: {\n data: PersistObject;\n options?: ExtraOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: R }>;\n\n abstract override createAll(opts: {\n data: Array<PersistObject>;\n options: ExtraOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract override createAll<R = DataObject>(opts: {\n data: Array<PersistObject>;\n options?: ExtraOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: Array<R> }>;\n\n abstract override updateById(opts: {\n id: IdType;\n data: Partial<PersistObject>;\n options: ExtraOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract override updateById<R = DataObject>(opts: {\n id: IdType;\n data: Partial<PersistObject>;\n options?: ExtraOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: R }>;\n\n abstract override updateAll(opts: {\n data: Partial<PersistObject>;\n where: TWhere<DataObject>;\n options: ExtraOptions & { shouldReturn: false; force?: boolean };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract override updateAll<R = DataObject>(opts: {\n data: Partial<PersistObject>;\n where: TWhere<DataObject>;\n options?: ExtraOptions & { shouldReturn?: true; force?: boolean };\n }): Promise<TCount & { data: Array<R> }>;\n\n // Re-declared, not inherited: the base alias is `Array<R> | null` to cover the search family, but SQL engines have RETURNING so this surface must stay exactly `Array<R>`.\n override updateBy(opts: {\n data: Partial<PersistObject>;\n where: TWhere<DataObject>;\n options: ExtraOptions & { shouldReturn: false; force?: boolean };\n }): Promise<TCount & { data: undefined | null }>;\n override updateBy<R = DataObject>(opts: {\n data: Partial<PersistObject>;\n where: TWhere<DataObject>;\n options?: ExtraOptions & { shouldReturn?: true; force?: boolean };\n }): Promise<TCount & { data: Array<R> }>;\n override updateBy<R = DataObject>(opts: {\n data: Partial<PersistObject>;\n where: TWhere<DataObject>;\n options?: ExtraOptions & { shouldReturn?: boolean; force?: boolean };\n }): Promise<TCount & { data: TNullable<Array<R>> }> {\n const { data, where, options } = opts;\n\n if (options?.shouldReturn === false) {\n return this.updateAll({ data, where, options: { ...options, shouldReturn: false } });\n }\n\n return this.updateAll<R>({ data, where, options });\n }\n\n abstract override deleteById(opts: {\n id: IdType;\n options: ExtraOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract override deleteById<R = DataObject>(opts: {\n id: IdType;\n options?: ExtraOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: R }>;\n\n abstract override deleteAll(opts: {\n where?: TWhere<DataObject>;\n options: ExtraOptions & { shouldReturn: false; force?: boolean };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract override deleteAll<R = DataObject>(opts: {\n where?: TWhere<DataObject>;\n options?: ExtraOptions & { shouldReturn?: true; force?: boolean };\n }): Promise<TCount & { data: Array<R> }>;\n\n // Same rationale as updateBy above: keep this alias surface at `Array<R>`.\n override deleteBy(opts: {\n where?: TWhere<DataObject>;\n options: ExtraOptions & { shouldReturn: false; force?: boolean };\n }): Promise<TCount & { data: undefined | null }>;\n override deleteBy<R = DataObject>(opts: {\n where?: TWhere<DataObject>;\n options?: ExtraOptions & { shouldReturn?: true; force?: boolean };\n }): Promise<TCount & { data: Array<R> }>;\n override deleteBy<R = DataObject>(opts: {\n where?: TWhere<DataObject>;\n options?: ExtraOptions & { shouldReturn?: boolean; force?: boolean };\n }): Promise<TCount & { data: TNullable<Array<R>> }> {\n const { where, options } = opts;\n\n if (options?.shouldReturn === false) {\n return this.deleteAll({ where, options: { ...options, shouldReturn: false } });\n }\n\n return this.deleteAll<R>({ where, options });\n }\n}\n"]}
|
|
@@ -69,7 +69,8 @@ export declare abstract class FilterBuilder extends BaseHelper {
|
|
|
69
69
|
}): TModelAccessSettings | undefined;
|
|
70
70
|
/**
|
|
71
71
|
* The foreign key link of a `through` model and the scope its parent resolves for `operation` (the same operation
|
|
72
|
-
* at every hop). The parent's default filter is not applied: scope only.
|
|
72
|
+
* at every hop). The parent's default filter is not applied: scope only. For a write the parent's scope is narrowed as a
|
|
73
|
+
* direct write to the parent is (`ScopeWriteGuard.mutationWhere`), so its `write.sharedRows` holds on the hop.
|
|
73
74
|
*/
|
|
74
75
|
resolveThrough(opts: {
|
|
75
76
|
settings: IModelAccessThroughSettings;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { EchoUtility } from '../../../../common/internal/index.js';
|
|
2
2
|
import { ScopeThroughLink } from '../common/scope-through.js';
|
|
3
|
+
import { ScopeWriteGuard } from '../common/scope-write-guard.js';
|
|
3
4
|
import { DEFAULT_LIMIT, QueryOperators, RelationTypes, ScopeFilterMissingBehaviors, ScopeFilters, ScopeOperations, Sorts, } from '@venizia/ignis-kernel';
|
|
4
5
|
import { BaseHelper, getError } from '@venizia/ignis-helpers/core';
|
|
5
6
|
import { ObjectUtility } from '@venizia/ignis-helpers/common';
|
|
@@ -160,7 +161,8 @@ export class FilterBuilder extends BaseHelper {
|
|
|
160
161
|
}
|
|
161
162
|
/**
|
|
162
163
|
* The foreign key link of a `through` model and the scope its parent resolves for `operation` (the same operation
|
|
163
|
-
* at every hop). The parent's default filter is not applied: scope only.
|
|
164
|
+
* at every hop). The parent's default filter is not applied: scope only. For a write the parent's scope is narrowed as a
|
|
165
|
+
* direct write to the parent is (`ScopeWriteGuard.mutationWhere`), so its `write.sharedRows` holds on the hop.
|
|
164
166
|
*/
|
|
165
167
|
resolveThrough(opts) {
|
|
166
168
|
const { settings, schema, operation, depth = 1 } = opts;
|
|
@@ -180,12 +182,27 @@ export class FilterBuilder extends BaseHelper {
|
|
|
180
182
|
message: `[resolveThrough] ${getTableName(link.parentSchema)} has no access setting, so ${getTableName(schema)} cannot be scoped through it`,
|
|
181
183
|
});
|
|
182
184
|
}
|
|
183
|
-
const
|
|
185
|
+
const parentScope = this.resolveAccessScope({
|
|
184
186
|
settings: parentSettings,
|
|
185
187
|
schema: link.parentSchema,
|
|
186
188
|
operation,
|
|
187
189
|
depth: depth + 1,
|
|
188
190
|
});
|
|
191
|
+
// A write to the child reaches the parent the way a write to the parent itself does: the shared (null) rows its read scope
|
|
192
|
+
// opens need the parent's `write.sharedRows`. A parent that is itself `through` narrowed its own parent on its hop.
|
|
193
|
+
const isNarrowed = ScopeOperations.includes({ group: ScopeOperations.WRITE, operation }) &&
|
|
194
|
+
!parentSettings.through &&
|
|
195
|
+
parentScope !== ScopeFilters.UNRESTRICTED &&
|
|
196
|
+
parentScope !== null &&
|
|
197
|
+
parentScope !== undefined;
|
|
198
|
+
const scope = isNarrowed
|
|
199
|
+
? ScopeWriteGuard.mutationWhere({
|
|
200
|
+
settings: parentSettings,
|
|
201
|
+
model: getTableName(link.parentSchema),
|
|
202
|
+
operation,
|
|
203
|
+
scopeWhere: parentScope,
|
|
204
|
+
})
|
|
205
|
+
: parentScope;
|
|
189
206
|
return { link, scope };
|
|
190
207
|
}
|
|
191
208
|
/** The parent's scope as a `where` on the parent table: the part both the read subquery and the write check build. */
|