@zenstackhq/plugin-policy 3.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1555 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var src_exports = {};
23
+ __export(src_exports, {
24
+ PolicyPlugin: () => PolicyPlugin
25
+ });
26
+ module.exports = __toCommonJS(src_exports);
27
+
28
+ // src/functions.ts
29
+ var import_common_helpers4 = require("@zenstackhq/common-helpers");
30
+ var import_runtime9 = require("@zenstackhq/runtime");
31
+ var import_kysely4 = require("kysely");
32
+
33
+ // src/policy-handler.ts
34
+ var import_common_helpers3 = require("@zenstackhq/common-helpers");
35
+ var import_runtime7 = require("@zenstackhq/runtime");
36
+ var import_schema4 = require("@zenstackhq/runtime/schema");
37
+ var import_kysely3 = require("kysely");
38
+ var import_ts_pattern3 = require("ts-pattern");
39
+
40
+ // src/column-collector.ts
41
+ var import_runtime = require("@zenstackhq/runtime");
42
+ var ColumnCollector = class extends import_runtime.KyselyUtils.DefaultOperationNodeVisitor {
43
+ static {
44
+ __name(this, "ColumnCollector");
45
+ }
46
+ columns = [];
47
+ collect(node) {
48
+ this.columns = [];
49
+ this.visitNode(node);
50
+ return this.columns;
51
+ }
52
+ visitColumn(node) {
53
+ if (!this.columns.includes(node.column.name)) {
54
+ this.columns.push(node.column.name);
55
+ }
56
+ }
57
+ };
58
+
59
+ // src/expression-transformer.ts
60
+ var import_common_helpers2 = require("@zenstackhq/common-helpers");
61
+ var import_runtime5 = require("@zenstackhq/runtime");
62
+ var import_schema3 = require("@zenstackhq/runtime/schema");
63
+ var import_kysely2 = require("kysely");
64
+ var import_ts_pattern2 = require("ts-pattern");
65
+
66
+ // src/expression-evaluator.ts
67
+ var import_common_helpers = require("@zenstackhq/common-helpers");
68
+ var import_ts_pattern = require("ts-pattern");
69
+ var import_schema = require("@zenstackhq/runtime/schema");
70
+ var ExpressionEvaluator = class {
71
+ static {
72
+ __name(this, "ExpressionEvaluator");
73
+ }
74
+ evaluate(expression, context) {
75
+ const result = (0, import_ts_pattern.match)(expression).when(import_schema.ExpressionUtils.isArray, (expr2) => this.evaluateArray(expr2, context)).when(import_schema.ExpressionUtils.isBinary, (expr2) => this.evaluateBinary(expr2, context)).when(import_schema.ExpressionUtils.isField, (expr2) => this.evaluateField(expr2, context)).when(import_schema.ExpressionUtils.isLiteral, (expr2) => this.evaluateLiteral(expr2)).when(import_schema.ExpressionUtils.isMember, (expr2) => this.evaluateMember(expr2, context)).when(import_schema.ExpressionUtils.isUnary, (expr2) => this.evaluateUnary(expr2, context)).when(import_schema.ExpressionUtils.isCall, (expr2) => this.evaluateCall(expr2, context)).when(import_schema.ExpressionUtils.isThis, () => context.thisValue).when(import_schema.ExpressionUtils.isNull, () => null).exhaustive();
76
+ return result ?? null;
77
+ }
78
+ evaluateCall(expr2, context) {
79
+ if (expr2.function === "auth") {
80
+ return context.auth;
81
+ } else {
82
+ throw new Error(`Unsupported call expression function: ${expr2.function}`);
83
+ }
84
+ }
85
+ evaluateUnary(expr2, context) {
86
+ return (0, import_ts_pattern.match)(expr2.op).with("!", () => !this.evaluate(expr2.operand, context)).exhaustive();
87
+ }
88
+ evaluateMember(expr2, context) {
89
+ let val = this.evaluate(expr2.receiver, context);
90
+ for (const member of expr2.members) {
91
+ val = val?.[member];
92
+ }
93
+ return val;
94
+ }
95
+ evaluateLiteral(expr2) {
96
+ return expr2.value;
97
+ }
98
+ evaluateField(expr2, context) {
99
+ return context.thisValue?.[expr2.field];
100
+ }
101
+ evaluateArray(expr2, context) {
102
+ return expr2.items.map((item) => this.evaluate(item, context));
103
+ }
104
+ evaluateBinary(expr2, context) {
105
+ if (expr2.op === "?" || expr2.op === "!" || expr2.op === "^") {
106
+ return this.evaluateCollectionPredicate(expr2, context);
107
+ }
108
+ const left = this.evaluate(expr2.left, context);
109
+ const right = this.evaluate(expr2.right, context);
110
+ return (0, import_ts_pattern.match)(expr2.op).with("==", () => left === right).with("!=", () => left !== right).with(">", () => left > right).with(">=", () => left >= right).with("<", () => left < right).with("<=", () => left <= right).with("&&", () => left && right).with("||", () => left || right).with("in", () => {
111
+ const _right = right ?? [];
112
+ (0, import_common_helpers.invariant)(Array.isArray(_right), 'expected array for "in" operator');
113
+ return _right.includes(left);
114
+ }).exhaustive();
115
+ }
116
+ evaluateCollectionPredicate(expr2, context) {
117
+ const op = expr2.op;
118
+ (0, import_common_helpers.invariant)(op === "?" || op === "!" || op === "^", 'expected "?" or "!" or "^" operator');
119
+ const left = this.evaluate(expr2.left, context);
120
+ if (!left) {
121
+ return false;
122
+ }
123
+ (0, import_common_helpers.invariant)(Array.isArray(left), "expected array");
124
+ return (0, import_ts_pattern.match)(op).with("?", () => left.some((item) => this.evaluate(expr2.right, {
125
+ ...context,
126
+ thisValue: item
127
+ }))).with("!", () => left.every((item) => this.evaluate(expr2.right, {
128
+ ...context,
129
+ thisValue: item
130
+ }))).with("^", () => !left.some((item) => this.evaluate(expr2.right, {
131
+ ...context,
132
+ thisValue: item
133
+ }))).exhaustive();
134
+ }
135
+ };
136
+
137
+ // src/utils.ts
138
+ var import_schema2 = require("@zenstackhq/runtime/schema");
139
+ var import_kysely = require("kysely");
140
+ function trueNode(dialect) {
141
+ return import_kysely.ValueNode.createImmediate(dialect.transformPrimitive(true, "Boolean", false));
142
+ }
143
+ __name(trueNode, "trueNode");
144
+ function falseNode(dialect) {
145
+ return import_kysely.ValueNode.createImmediate(dialect.transformPrimitive(false, "Boolean", false));
146
+ }
147
+ __name(falseNode, "falseNode");
148
+ function isTrueNode(node) {
149
+ return import_kysely.ValueNode.is(node) && (node.value === true || node.value === 1);
150
+ }
151
+ __name(isTrueNode, "isTrueNode");
152
+ function isFalseNode(node) {
153
+ return import_kysely.ValueNode.is(node) && (node.value === false || node.value === 0);
154
+ }
155
+ __name(isFalseNode, "isFalseNode");
156
+ function conjunction(dialect, nodes) {
157
+ if (nodes.length === 0) {
158
+ return trueNode(dialect);
159
+ }
160
+ if (nodes.length === 1) {
161
+ return nodes[0];
162
+ }
163
+ if (nodes.some(isFalseNode)) {
164
+ return falseNode(dialect);
165
+ }
166
+ const items = nodes.filter((n) => !isTrueNode(n));
167
+ if (items.length === 0) {
168
+ return trueNode(dialect);
169
+ }
170
+ return items.reduce((acc, node) => import_kysely.AndNode.create(wrapParensIf(acc, import_kysely.OrNode.is), wrapParensIf(node, import_kysely.OrNode.is)));
171
+ }
172
+ __name(conjunction, "conjunction");
173
+ function disjunction(dialect, nodes) {
174
+ if (nodes.length === 0) {
175
+ return falseNode(dialect);
176
+ }
177
+ if (nodes.length === 1) {
178
+ return nodes[0];
179
+ }
180
+ if (nodes.some(isTrueNode)) {
181
+ return trueNode(dialect);
182
+ }
183
+ const items = nodes.filter((n) => !isFalseNode(n));
184
+ if (items.length === 0) {
185
+ return falseNode(dialect);
186
+ }
187
+ return items.reduce((acc, node) => import_kysely.OrNode.create(wrapParensIf(acc, import_kysely.AndNode.is), wrapParensIf(node, import_kysely.AndNode.is)));
188
+ }
189
+ __name(disjunction, "disjunction");
190
+ function logicalNot(dialect, node) {
191
+ if (isTrueNode(node)) {
192
+ return falseNode(dialect);
193
+ }
194
+ if (isFalseNode(node)) {
195
+ return trueNode(dialect);
196
+ }
197
+ return import_kysely.UnaryOperationNode.create(import_kysely.OperatorNode.create("not"), wrapParensIf(node, (n) => import_kysely.AndNode.is(n) || import_kysely.OrNode.is(n)));
198
+ }
199
+ __name(logicalNot, "logicalNot");
200
+ function wrapParensIf(node, predicate) {
201
+ return predicate(node) ? import_kysely.ParensNode.create(node) : node;
202
+ }
203
+ __name(wrapParensIf, "wrapParensIf");
204
+ function buildIsFalse(node, dialect) {
205
+ if (isFalseNode(node)) {
206
+ return trueNode(dialect);
207
+ } else if (isTrueNode(node)) {
208
+ return falseNode(dialect);
209
+ }
210
+ return import_kysely.BinaryOperationNode.create(
211
+ // coalesce so null is treated as false
212
+ import_kysely.FunctionNode.create("coalesce", [
213
+ node,
214
+ falseNode(dialect)
215
+ ]),
216
+ import_kysely.OperatorNode.create("="),
217
+ falseNode(dialect)
218
+ );
219
+ }
220
+ __name(buildIsFalse, "buildIsFalse");
221
+ function getTableName(node) {
222
+ if (!node) {
223
+ return node;
224
+ }
225
+ if (import_kysely.TableNode.is(node)) {
226
+ return node.table.identifier.name;
227
+ } else if (import_kysely.AliasNode.is(node)) {
228
+ return getTableName(node.node);
229
+ } else if (import_kysely.ReferenceNode.is(node) && node.table) {
230
+ return getTableName(node.table);
231
+ }
232
+ return void 0;
233
+ }
234
+ __name(getTableName, "getTableName");
235
+ function isBeforeInvocation(expr2) {
236
+ return import_schema2.ExpressionUtils.isCall(expr2) && expr2.function === "before";
237
+ }
238
+ __name(isBeforeInvocation, "isBeforeInvocation");
239
+
240
+ // src/expression-transformer.ts
241
+ function _ts_decorate(decorators, target, key, desc) {
242
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
243
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
244
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
245
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
246
+ }
247
+ __name(_ts_decorate, "_ts_decorate");
248
+ function _ts_metadata(k, v) {
249
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
250
+ }
251
+ __name(_ts_metadata, "_ts_metadata");
252
+ var expressionHandlers = /* @__PURE__ */ new Map();
253
+ function expr(kind) {
254
+ return function(_target, _propertyKey, descriptor) {
255
+ if (!expressionHandlers.get(kind)) {
256
+ expressionHandlers.set(kind, descriptor);
257
+ }
258
+ return descriptor;
259
+ };
260
+ }
261
+ __name(expr, "expr");
262
+ var ExpressionTransformer = class {
263
+ static {
264
+ __name(this, "ExpressionTransformer");
265
+ }
266
+ client;
267
+ dialect;
268
+ constructor(client) {
269
+ this.client = client;
270
+ this.dialect = (0, import_runtime5.getCrudDialect)(this.schema, this.clientOptions);
271
+ }
272
+ get schema() {
273
+ return this.client.$schema;
274
+ }
275
+ get clientOptions() {
276
+ return this.client.$options;
277
+ }
278
+ get auth() {
279
+ return this.client.$auth;
280
+ }
281
+ get authType() {
282
+ if (!this.schema.authType) {
283
+ throw new import_runtime5.InternalError('Schema does not have an "authType" specified');
284
+ }
285
+ return this.schema.authType;
286
+ }
287
+ transform(expression, context) {
288
+ const handler = expressionHandlers.get(expression.kind);
289
+ if (!handler) {
290
+ throw new Error(`Unsupported expression kind: ${expression.kind}`);
291
+ }
292
+ return handler.value.call(this, expression, context);
293
+ }
294
+ _literal(expr2) {
295
+ return this.transformValue(expr2.value, typeof expr2.value === "string" ? "String" : typeof expr2.value === "boolean" ? "Boolean" : "Int");
296
+ }
297
+ _array(expr2, context) {
298
+ return import_kysely2.ValueListNode.create(expr2.items.map((item) => this.transform(item, context)));
299
+ }
300
+ _field(expr2, context) {
301
+ const fieldDef = import_runtime5.QueryUtils.requireField(this.schema, context.model, expr2.field);
302
+ if (!fieldDef.relation) {
303
+ return this.createColumnRef(expr2.field, context);
304
+ } else {
305
+ const { memberFilter, memberSelect, ...restContext } = context;
306
+ const relation = this.transformRelationAccess(expr2.field, fieldDef.type, restContext);
307
+ return {
308
+ ...relation,
309
+ where: this.mergeWhere(relation.where, memberFilter),
310
+ selections: memberSelect ? [
311
+ memberSelect
312
+ ] : relation.selections
313
+ };
314
+ }
315
+ }
316
+ mergeWhere(where, memberFilter) {
317
+ if (!where) {
318
+ return import_kysely2.WhereNode.create(memberFilter ?? trueNode(this.dialect));
319
+ }
320
+ if (!memberFilter) {
321
+ return where;
322
+ }
323
+ return import_kysely2.WhereNode.create(conjunction(this.dialect, [
324
+ where.where,
325
+ memberFilter
326
+ ]));
327
+ }
328
+ _null() {
329
+ return import_kysely2.ValueNode.createImmediate(null);
330
+ }
331
+ _binary(expr2, context) {
332
+ if (expr2.op === "&&") {
333
+ return conjunction(this.dialect, [
334
+ this.transform(expr2.left, context),
335
+ this.transform(expr2.right, context)
336
+ ]);
337
+ } else if (expr2.op === "||") {
338
+ return disjunction(this.dialect, [
339
+ this.transform(expr2.left, context),
340
+ this.transform(expr2.right, context)
341
+ ]);
342
+ }
343
+ if (this.isAuthCall(expr2.left) || this.isAuthCall(expr2.right)) {
344
+ return this.transformAuthBinary(expr2, context);
345
+ }
346
+ const op = expr2.op;
347
+ if (op === "?" || op === "!" || op === "^") {
348
+ return this.transformCollectionPredicate(expr2, context);
349
+ }
350
+ const { normalizedLeft, normalizedRight } = this.normalizeBinaryOperationOperands(expr2, context);
351
+ const left = this.transform(normalizedLeft, context);
352
+ const right = this.transform(normalizedRight, context);
353
+ if (op === "in") {
354
+ if (this.isNullNode(left)) {
355
+ return this.transformValue(false, "Boolean");
356
+ } else {
357
+ if (import_kysely2.ValueListNode.is(right)) {
358
+ return import_kysely2.BinaryOperationNode.create(left, import_kysely2.OperatorNode.create("in"), right);
359
+ } else {
360
+ return import_kysely2.BinaryOperationNode.create(left, import_kysely2.OperatorNode.create("="), import_kysely2.FunctionNode.create("any", [
361
+ right
362
+ ]));
363
+ }
364
+ }
365
+ }
366
+ if (this.isNullNode(right)) {
367
+ return this.transformNullCheck(left, expr2.op);
368
+ } else if (this.isNullNode(left)) {
369
+ return this.transformNullCheck(right, expr2.op);
370
+ } else {
371
+ return import_kysely2.BinaryOperationNode.create(left, this.transformOperator(op), right);
372
+ }
373
+ }
374
+ transformNullCheck(expr2, operator) {
375
+ (0, import_common_helpers2.invariant)(operator === "==" || operator === "!=", 'operator must be "==" or "!=" for null comparison');
376
+ if (import_kysely2.ValueNode.is(expr2)) {
377
+ if (expr2.value === null) {
378
+ return operator === "==" ? trueNode(this.dialect) : falseNode(this.dialect);
379
+ } else {
380
+ return operator === "==" ? falseNode(this.dialect) : trueNode(this.dialect);
381
+ }
382
+ } else {
383
+ return operator === "==" ? import_kysely2.BinaryOperationNode.create(expr2, import_kysely2.OperatorNode.create("is"), import_kysely2.ValueNode.createImmediate(null)) : import_kysely2.BinaryOperationNode.create(expr2, import_kysely2.OperatorNode.create("is not"), import_kysely2.ValueNode.createImmediate(null));
384
+ }
385
+ }
386
+ normalizeBinaryOperationOperands(expr2, context) {
387
+ let normalizedLeft = expr2.left;
388
+ if (this.isRelationField(expr2.left, context.model)) {
389
+ (0, import_common_helpers2.invariant)(import_schema3.ExpressionUtils.isNull(expr2.right), "only null comparison is supported for relation field");
390
+ const leftRelDef = this.getFieldDefFromFieldRef(expr2.left, context.model);
391
+ (0, import_common_helpers2.invariant)(leftRelDef, "failed to get relation field definition");
392
+ const idFields = import_runtime5.QueryUtils.requireIdFields(this.schema, leftRelDef.type);
393
+ normalizedLeft = this.makeOrAppendMember(normalizedLeft, idFields[0]);
394
+ }
395
+ let normalizedRight = expr2.right;
396
+ if (this.isRelationField(expr2.right, context.model)) {
397
+ (0, import_common_helpers2.invariant)(import_schema3.ExpressionUtils.isNull(expr2.left), "only null comparison is supported for relation field");
398
+ const rightRelDef = this.getFieldDefFromFieldRef(expr2.right, context.model);
399
+ (0, import_common_helpers2.invariant)(rightRelDef, "failed to get relation field definition");
400
+ const idFields = import_runtime5.QueryUtils.requireIdFields(this.schema, rightRelDef.type);
401
+ normalizedRight = this.makeOrAppendMember(normalizedRight, idFields[0]);
402
+ }
403
+ return {
404
+ normalizedLeft,
405
+ normalizedRight
406
+ };
407
+ }
408
+ transformCollectionPredicate(expr2, context) {
409
+ (0, import_common_helpers2.invariant)(expr2.op === "?" || expr2.op === "!" || expr2.op === "^", 'expected "?" or "!" or "^" operator');
410
+ if (this.isAuthCall(expr2.left) || this.isAuthMember(expr2.left)) {
411
+ const value = new ExpressionEvaluator().evaluate(expr2, {
412
+ auth: this.auth
413
+ });
414
+ return this.transformValue(value, "Boolean");
415
+ }
416
+ (0, import_common_helpers2.invariant)(import_schema3.ExpressionUtils.isField(expr2.left) || import_schema3.ExpressionUtils.isMember(expr2.left), "left operand must be field or member access");
417
+ let newContextModel;
418
+ const fieldDef = this.getFieldDefFromFieldRef(expr2.left, context.model);
419
+ if (fieldDef) {
420
+ (0, import_common_helpers2.invariant)(fieldDef.relation, `field is not a relation: ${JSON.stringify(expr2.left)}`);
421
+ newContextModel = fieldDef.type;
422
+ } else {
423
+ (0, import_common_helpers2.invariant)(import_schema3.ExpressionUtils.isMember(expr2.left) && import_schema3.ExpressionUtils.isField(expr2.left.receiver), "left operand must be member access with field receiver");
424
+ const fieldDef2 = import_runtime5.QueryUtils.requireField(this.schema, context.model, expr2.left.receiver.field);
425
+ newContextModel = fieldDef2.type;
426
+ for (const member of expr2.left.members) {
427
+ const memberDef = import_runtime5.QueryUtils.requireField(this.schema, newContextModel, member);
428
+ newContextModel = memberDef.type;
429
+ }
430
+ }
431
+ let predicateFilter = this.transform(expr2.right, {
432
+ ...context,
433
+ model: newContextModel,
434
+ alias: void 0
435
+ });
436
+ if (expr2.op === "!") {
437
+ predicateFilter = logicalNot(this.dialect, predicateFilter);
438
+ }
439
+ const count = import_kysely2.FunctionNode.create("count", [
440
+ import_kysely2.ValueNode.createImmediate(1)
441
+ ]);
442
+ const predicateResult = (0, import_ts_pattern2.match)(expr2.op).with("?", () => import_kysely2.BinaryOperationNode.create(count, import_kysely2.OperatorNode.create(">"), import_kysely2.ValueNode.createImmediate(0))).with("!", () => import_kysely2.BinaryOperationNode.create(count, import_kysely2.OperatorNode.create("="), import_kysely2.ValueNode.createImmediate(0))).with("^", () => import_kysely2.BinaryOperationNode.create(count, import_kysely2.OperatorNode.create("="), import_kysely2.ValueNode.createImmediate(0))).exhaustive();
443
+ return this.transform(expr2.left, {
444
+ ...context,
445
+ memberSelect: import_kysely2.SelectionNode.create(import_kysely2.AliasNode.create(predicateResult, import_kysely2.IdentifierNode.create("$t"))),
446
+ memberFilter: predicateFilter
447
+ });
448
+ }
449
+ transformAuthBinary(expr2, context) {
450
+ if (expr2.op !== "==" && expr2.op !== "!=") {
451
+ throw new import_runtime5.QueryError(`Unsupported operator for \`auth()\` in policy of model "${context.model}": ${expr2.op}`);
452
+ }
453
+ let authExpr;
454
+ let other;
455
+ if (this.isAuthCall(expr2.left)) {
456
+ authExpr = expr2.left;
457
+ other = expr2.right;
458
+ } else {
459
+ authExpr = expr2.right;
460
+ other = expr2.left;
461
+ }
462
+ if (import_schema3.ExpressionUtils.isNull(other)) {
463
+ return this.transformValue(expr2.op === "==" ? !this.auth : !!this.auth, "Boolean");
464
+ } else {
465
+ const authModel = import_runtime5.QueryUtils.getModel(this.schema, this.authType);
466
+ if (!authModel) {
467
+ throw new import_runtime5.QueryError(`Unsupported use of \`auth()\` in policy of model "${context.model}", comparing with \`auth()\` is only possible when auth type is a model`);
468
+ }
469
+ const idFields = Object.values(authModel.fields).filter((f) => f.id).map((f) => f.name);
470
+ (0, import_common_helpers2.invariant)(idFields.length > 0, "auth type model must have at least one id field");
471
+ const conditions = idFields.map((fieldName) => import_schema3.ExpressionUtils.binary(import_schema3.ExpressionUtils.member(authExpr, [
472
+ fieldName
473
+ ]), "==", this.makeOrAppendMember(other, fieldName)));
474
+ let result = this.buildAnd(conditions);
475
+ if (expr2.op === "!=") {
476
+ result = this.buildLogicalNot(result);
477
+ }
478
+ return this.transform(result, context);
479
+ }
480
+ }
481
+ makeOrAppendMember(other, fieldName) {
482
+ if (import_schema3.ExpressionUtils.isMember(other)) {
483
+ return import_schema3.ExpressionUtils.member(other.receiver, [
484
+ ...other.members,
485
+ fieldName
486
+ ]);
487
+ } else {
488
+ return import_schema3.ExpressionUtils.member(other, [
489
+ fieldName
490
+ ]);
491
+ }
492
+ }
493
+ transformValue(value, type) {
494
+ if (value === true) {
495
+ return trueNode(this.dialect);
496
+ } else if (value === false) {
497
+ return falseNode(this.dialect);
498
+ } else {
499
+ return import_kysely2.ValueNode.create(this.dialect.transformPrimitive(value, type, false) ?? null);
500
+ }
501
+ }
502
+ _unary(expr2, context) {
503
+ (0, import_common_helpers2.invariant)(expr2.op === "!", 'only "!" operator is supported');
504
+ return logicalNot(this.dialect, this.transform(expr2.operand, context));
505
+ }
506
+ transformOperator(op) {
507
+ const mappedOp = (0, import_ts_pattern2.match)(op).with("==", () => "=").otherwise(() => op);
508
+ return import_kysely2.OperatorNode.create(mappedOp);
509
+ }
510
+ _call(expr2, context) {
511
+ const result = this.transformCall(expr2, context);
512
+ return result.toOperationNode();
513
+ }
514
+ transformCall(expr2, context) {
515
+ const func = this.getFunctionImpl(expr2.function);
516
+ if (!func) {
517
+ throw new import_runtime5.QueryError(`Function not implemented: ${expr2.function}`);
518
+ }
519
+ const eb = (0, import_kysely2.expressionBuilder)();
520
+ return func(eb, (expr2.args ?? []).map((arg) => this.transformCallArg(eb, arg, context)), {
521
+ client: this.client,
522
+ dialect: this.dialect,
523
+ model: context.model,
524
+ modelAlias: context.alias ?? context.model,
525
+ operation: context.operation
526
+ });
527
+ }
528
+ getFunctionImpl(functionName) {
529
+ let func = this.clientOptions.functions?.[functionName];
530
+ if (!func) {
531
+ for (const plugin of this.clientOptions.plugins ?? []) {
532
+ if (plugin.functions?.[functionName]) {
533
+ func = plugin.functions[functionName];
534
+ break;
535
+ }
536
+ }
537
+ }
538
+ return func;
539
+ }
540
+ transformCallArg(eb, arg, context) {
541
+ if (import_schema3.ExpressionUtils.isLiteral(arg)) {
542
+ return eb.val(arg.value);
543
+ }
544
+ if (import_schema3.ExpressionUtils.isField(arg)) {
545
+ return eb.ref(arg.field);
546
+ }
547
+ if (import_schema3.ExpressionUtils.isCall(arg)) {
548
+ return this.transformCall(arg, context);
549
+ }
550
+ if (this.isAuthMember(arg)) {
551
+ const valNode = this.valueMemberAccess(this.auth, arg, this.authType);
552
+ return valNode ? eb.val(valNode.value) : eb.val(null);
553
+ }
554
+ throw new import_runtime5.InternalError(`Unsupported argument expression: ${arg.kind}`);
555
+ }
556
+ _member(expr2, context) {
557
+ if (this.isAuthCall(expr2.receiver)) {
558
+ return this.valueMemberAccess(this.auth, expr2, this.authType);
559
+ }
560
+ if (isBeforeInvocation(expr2.receiver)) {
561
+ (0, import_common_helpers2.invariant)(context.operation === "post-update", "before() can only be used in post-update policy");
562
+ (0, import_common_helpers2.invariant)(expr2.members.length === 1, "before() can only be followed by a scalar field access");
563
+ return import_kysely2.ReferenceNode.create(import_kysely2.ColumnNode.create(expr2.members[0]), import_kysely2.TableNode.create("$before"));
564
+ }
565
+ (0, import_common_helpers2.invariant)(import_schema3.ExpressionUtils.isField(expr2.receiver) || import_schema3.ExpressionUtils.isThis(expr2.receiver), 'expect receiver to be field expression or "this"');
566
+ let members = expr2.members;
567
+ let receiver;
568
+ const { memberFilter, memberSelect, ...restContext } = context;
569
+ if (import_schema3.ExpressionUtils.isThis(expr2.receiver)) {
570
+ if (expr2.members.length === 1) {
571
+ return this._field(import_schema3.ExpressionUtils.field(expr2.members[0]), context);
572
+ } else {
573
+ const firstMemberFieldDef = import_runtime5.QueryUtils.requireField(this.schema, context.model, expr2.members[0]);
574
+ receiver = this.transformRelationAccess(expr2.members[0], firstMemberFieldDef.type, restContext);
575
+ members = expr2.members.slice(1);
576
+ }
577
+ } else {
578
+ receiver = this.transform(expr2.receiver, restContext);
579
+ }
580
+ (0, import_common_helpers2.invariant)(import_kysely2.SelectQueryNode.is(receiver), "expected receiver to be select query");
581
+ let startType;
582
+ if (import_schema3.ExpressionUtils.isField(expr2.receiver)) {
583
+ const receiverField = import_runtime5.QueryUtils.requireField(this.schema, context.model, expr2.receiver.field);
584
+ startType = receiverField.type;
585
+ } else {
586
+ startType = context.model;
587
+ }
588
+ const memberFields = [];
589
+ let currType = startType;
590
+ for (const member of members) {
591
+ const fieldDef = import_runtime5.QueryUtils.requireField(this.schema, currType, member);
592
+ memberFields.push({
593
+ fieldDef,
594
+ fromModel: currType
595
+ });
596
+ currType = fieldDef.type;
597
+ }
598
+ let currNode = void 0;
599
+ for (let i = members.length - 1; i >= 0; i--) {
600
+ const member = members[i];
601
+ const { fieldDef, fromModel } = memberFields[i];
602
+ if (fieldDef.relation) {
603
+ const relation = this.transformRelationAccess(member, fieldDef.type, {
604
+ ...restContext,
605
+ model: fromModel,
606
+ alias: void 0
607
+ });
608
+ if (currNode) {
609
+ currNode = {
610
+ ...relation,
611
+ selections: [
612
+ import_kysely2.SelectionNode.create(import_kysely2.AliasNode.create(currNode, import_kysely2.IdentifierNode.create(members[i + 1])))
613
+ ]
614
+ };
615
+ } else {
616
+ currNode = {
617
+ ...relation,
618
+ where: this.mergeWhere(relation.where, memberFilter),
619
+ selections: memberSelect ? [
620
+ memberSelect
621
+ ] : relation.selections
622
+ };
623
+ }
624
+ } else {
625
+ (0, import_common_helpers2.invariant)(i === members.length - 1, "plain field access must be the last segment");
626
+ (0, import_common_helpers2.invariant)(!currNode, "plain field access must be the last segment");
627
+ currNode = import_kysely2.ColumnNode.create(member);
628
+ }
629
+ }
630
+ return {
631
+ ...receiver,
632
+ selections: [
633
+ import_kysely2.SelectionNode.create(import_kysely2.AliasNode.create(currNode, import_kysely2.IdentifierNode.create("$t")))
634
+ ]
635
+ };
636
+ }
637
+ valueMemberAccess(receiver, expr2, receiverType) {
638
+ if (!receiver) {
639
+ return import_kysely2.ValueNode.createImmediate(null);
640
+ }
641
+ if (expr2.members.length !== 1) {
642
+ throw new Error(`Only single member access is supported`);
643
+ }
644
+ const field = expr2.members[0];
645
+ const fieldDef = import_runtime5.QueryUtils.requireField(this.schema, receiverType, field);
646
+ const fieldValue = receiver[field] ?? null;
647
+ return this.transformValue(fieldValue, fieldDef.type);
648
+ }
649
+ transformRelationAccess(field, relationModel, context) {
650
+ const m2m = import_runtime5.QueryUtils.getManyToManyRelation(this.schema, context.model, field);
651
+ if (m2m) {
652
+ return this.transformManyToManyRelationAccess(m2m, context);
653
+ }
654
+ const fromModel = context.model;
655
+ const relationFieldDef = import_runtime5.QueryUtils.requireField(this.schema, fromModel, field);
656
+ const { keyPairs, ownedByModel } = import_runtime5.QueryUtils.getRelationForeignKeyFieldPairs(this.schema, fromModel, field);
657
+ let condition;
658
+ if (ownedByModel) {
659
+ condition = conjunction(this.dialect, keyPairs.map(({ fk, pk }) => {
660
+ let fkRef = import_kysely2.ReferenceNode.create(import_kysely2.ColumnNode.create(fk), import_kysely2.TableNode.create(context.alias ?? fromModel));
661
+ if (relationFieldDef.originModel && relationFieldDef.originModel !== fromModel) {
662
+ fkRef = this.buildDelegateBaseFieldSelect(fromModel, context.alias ?? fromModel, fk, relationFieldDef.originModel);
663
+ }
664
+ return import_kysely2.BinaryOperationNode.create(fkRef, import_kysely2.OperatorNode.create("="), import_kysely2.ReferenceNode.create(import_kysely2.ColumnNode.create(pk), import_kysely2.TableNode.create(relationModel)));
665
+ }));
666
+ } else {
667
+ condition = conjunction(this.dialect, keyPairs.map(({ fk, pk }) => import_kysely2.BinaryOperationNode.create(import_kysely2.ReferenceNode.create(import_kysely2.ColumnNode.create(pk), import_kysely2.TableNode.create(context.alias ?? fromModel)), import_kysely2.OperatorNode.create("="), import_kysely2.ReferenceNode.create(import_kysely2.ColumnNode.create(fk), import_kysely2.TableNode.create(relationModel)))));
668
+ }
669
+ return {
670
+ kind: "SelectQueryNode",
671
+ from: import_kysely2.FromNode.create([
672
+ import_kysely2.TableNode.create(relationModel)
673
+ ]),
674
+ where: import_kysely2.WhereNode.create(condition)
675
+ };
676
+ }
677
+ transformManyToManyRelationAccess(m2m, context) {
678
+ const eb = (0, import_kysely2.expressionBuilder)();
679
+ const relationQuery = eb.selectFrom(m2m.otherModel).innerJoin(m2m.joinTable, (join) => join.onRef(`${m2m.otherModel}.${m2m.otherPKName}`, "=", `${m2m.joinTable}.${m2m.otherFkName}`).onRef(`${m2m.joinTable}.${m2m.parentFkName}`, "=", `${context.alias ?? context.model}.${m2m.parentPKName}`));
680
+ return relationQuery.toOperationNode();
681
+ }
682
+ createColumnRef(column, context) {
683
+ const tableName = context.alias ?? context.model;
684
+ if (context.operation === "create") {
685
+ return import_kysely2.ReferenceNode.create(import_kysely2.ColumnNode.create(column), import_kysely2.TableNode.create(tableName));
686
+ }
687
+ const fieldDef = import_runtime5.QueryUtils.requireField(this.schema, context.model, column);
688
+ if (!fieldDef.originModel || fieldDef.originModel === context.model) {
689
+ return import_kysely2.ReferenceNode.create(import_kysely2.ColumnNode.create(column), import_kysely2.TableNode.create(tableName));
690
+ }
691
+ return this.buildDelegateBaseFieldSelect(context.model, tableName, column, fieldDef.originModel);
692
+ }
693
+ buildDelegateBaseFieldSelect(model, modelAlias, field, baseModel) {
694
+ const idFields = import_runtime5.QueryUtils.requireIdFields(this.client.$schema, model);
695
+ return {
696
+ kind: "SelectQueryNode",
697
+ from: import_kysely2.FromNode.create([
698
+ import_kysely2.TableNode.create(baseModel)
699
+ ]),
700
+ selections: [
701
+ import_kysely2.SelectionNode.create(import_kysely2.ReferenceNode.create(import_kysely2.ColumnNode.create(field), import_kysely2.TableNode.create(baseModel)))
702
+ ],
703
+ where: import_kysely2.WhereNode.create(conjunction(this.dialect, idFields.map((idField) => import_kysely2.BinaryOperationNode.create(import_kysely2.ReferenceNode.create(import_kysely2.ColumnNode.create(idField), import_kysely2.TableNode.create(baseModel)), import_kysely2.OperatorNode.create("="), import_kysely2.ReferenceNode.create(import_kysely2.ColumnNode.create(idField), import_kysely2.TableNode.create(modelAlias))))))
704
+ };
705
+ }
706
+ isAuthCall(value) {
707
+ return import_schema3.ExpressionUtils.isCall(value) && value.function === "auth";
708
+ }
709
+ isAuthMember(expr2) {
710
+ return import_schema3.ExpressionUtils.isMember(expr2) && this.isAuthCall(expr2.receiver);
711
+ }
712
+ isNullNode(node) {
713
+ return import_kysely2.ValueNode.is(node) && node.value === null;
714
+ }
715
+ buildLogicalNot(result) {
716
+ return import_schema3.ExpressionUtils.unary("!", result);
717
+ }
718
+ buildAnd(conditions) {
719
+ if (conditions.length === 0) {
720
+ return import_schema3.ExpressionUtils.literal(true);
721
+ } else if (conditions.length === 1) {
722
+ return conditions[0];
723
+ } else {
724
+ return conditions.reduce((acc, condition) => import_schema3.ExpressionUtils.binary(acc, "&&", condition));
725
+ }
726
+ }
727
+ isRelationField(expr2, model) {
728
+ const fieldDef = this.getFieldDefFromFieldRef(expr2, model);
729
+ return !!fieldDef?.relation;
730
+ }
731
+ getFieldDefFromFieldRef(expr2, model) {
732
+ if (import_schema3.ExpressionUtils.isField(expr2)) {
733
+ return import_runtime5.QueryUtils.requireField(this.schema, model, expr2.field);
734
+ } else if (import_schema3.ExpressionUtils.isMember(expr2) && expr2.members.length === 1 && import_schema3.ExpressionUtils.isThis(expr2.receiver)) {
735
+ return import_runtime5.QueryUtils.requireField(this.schema, model, expr2.members[0]);
736
+ } else {
737
+ return void 0;
738
+ }
739
+ }
740
+ };
741
+ _ts_decorate([
742
+ expr("literal"),
743
+ _ts_metadata("design:type", Function),
744
+ _ts_metadata("design:paramtypes", [
745
+ typeof LiteralExpression === "undefined" ? Object : LiteralExpression
746
+ ]),
747
+ _ts_metadata("design:returntype", void 0)
748
+ ], ExpressionTransformer.prototype, "_literal", null);
749
+ _ts_decorate([
750
+ expr("array"),
751
+ _ts_metadata("design:type", Function),
752
+ _ts_metadata("design:paramtypes", [
753
+ typeof ArrayExpression === "undefined" ? Object : ArrayExpression,
754
+ typeof ExpressionTransformerContext === "undefined" ? Object : ExpressionTransformerContext
755
+ ]),
756
+ _ts_metadata("design:returntype", void 0)
757
+ ], ExpressionTransformer.prototype, "_array", null);
758
+ _ts_decorate([
759
+ expr("field"),
760
+ _ts_metadata("design:type", Function),
761
+ _ts_metadata("design:paramtypes", [
762
+ typeof FieldExpression === "undefined" ? Object : FieldExpression,
763
+ typeof ExpressionTransformerContext === "undefined" ? Object : ExpressionTransformerContext
764
+ ]),
765
+ _ts_metadata("design:returntype", void 0)
766
+ ], ExpressionTransformer.prototype, "_field", null);
767
+ _ts_decorate([
768
+ expr("null"),
769
+ _ts_metadata("design:type", Function),
770
+ _ts_metadata("design:paramtypes", []),
771
+ _ts_metadata("design:returntype", void 0)
772
+ ], ExpressionTransformer.prototype, "_null", null);
773
+ _ts_decorate([
774
+ expr("binary"),
775
+ _ts_metadata("design:type", Function),
776
+ _ts_metadata("design:paramtypes", [
777
+ typeof BinaryExpression === "undefined" ? Object : BinaryExpression,
778
+ typeof ExpressionTransformerContext === "undefined" ? Object : ExpressionTransformerContext
779
+ ]),
780
+ _ts_metadata("design:returntype", void 0)
781
+ ], ExpressionTransformer.prototype, "_binary", null);
782
+ _ts_decorate([
783
+ expr("unary"),
784
+ _ts_metadata("design:type", Function),
785
+ _ts_metadata("design:paramtypes", [
786
+ typeof UnaryExpression === "undefined" ? Object : UnaryExpression,
787
+ typeof ExpressionTransformerContext === "undefined" ? Object : ExpressionTransformerContext
788
+ ]),
789
+ _ts_metadata("design:returntype", void 0)
790
+ ], ExpressionTransformer.prototype, "_unary", null);
791
+ _ts_decorate([
792
+ expr("call"),
793
+ _ts_metadata("design:type", Function),
794
+ _ts_metadata("design:paramtypes", [
795
+ typeof CallExpression === "undefined" ? Object : CallExpression,
796
+ typeof ExpressionTransformerContext === "undefined" ? Object : ExpressionTransformerContext
797
+ ]),
798
+ _ts_metadata("design:returntype", void 0)
799
+ ], ExpressionTransformer.prototype, "_call", null);
800
+ _ts_decorate([
801
+ expr("member"),
802
+ _ts_metadata("design:type", Function),
803
+ _ts_metadata("design:paramtypes", [
804
+ typeof MemberExpression === "undefined" ? Object : MemberExpression,
805
+ typeof ExpressionTransformerContext === "undefined" ? Object : ExpressionTransformerContext
806
+ ]),
807
+ _ts_metadata("design:returntype", void 0)
808
+ ], ExpressionTransformer.prototype, "_member", null);
809
+
810
+ // src/policy-handler.ts
811
+ var PolicyHandler = class extends import_kysely3.OperationNodeTransformer {
812
+ static {
813
+ __name(this, "PolicyHandler");
814
+ }
815
+ client;
816
+ dialect;
817
+ constructor(client) {
818
+ super(), this.client = client;
819
+ this.dialect = (0, import_runtime7.getCrudDialect)(this.client.$schema, this.client.$options);
820
+ }
821
+ get kysely() {
822
+ return this.client.$qb;
823
+ }
824
+ async handle(node, proceed) {
825
+ if (!this.isCrudQueryNode(node)) {
826
+ throw new import_runtime7.RejectedByPolicyError(void 0, import_runtime7.RejectedByPolicyReason.OTHER, "non-CRUD queries are not allowed");
827
+ }
828
+ if (!this.isMutationQueryNode(node)) {
829
+ return proceed(this.transformNode(node));
830
+ }
831
+ const { mutationModel } = this.getMutationModel(node);
832
+ if (import_kysely3.InsertQueryNode.is(node)) {
833
+ const isManyToManyJoinTable = this.isManyToManyJoinTable(mutationModel);
834
+ let needCheckPreCreate = true;
835
+ if (!isManyToManyJoinTable) {
836
+ const constCondition = this.tryGetConstantPolicy(mutationModel, "create");
837
+ if (constCondition === true) {
838
+ needCheckPreCreate = false;
839
+ } else if (constCondition === false) {
840
+ throw new import_runtime7.RejectedByPolicyError(mutationModel);
841
+ }
842
+ }
843
+ if (needCheckPreCreate) {
844
+ await this.enforcePreCreatePolicy(node, mutationModel, isManyToManyJoinTable, proceed);
845
+ }
846
+ }
847
+ const hasPostUpdatePolicies = import_kysely3.UpdateQueryNode.is(node) && this.hasPostUpdatePolicies(mutationModel);
848
+ let beforeUpdateInfo;
849
+ if (hasPostUpdatePolicies) {
850
+ beforeUpdateInfo = await this.loadBeforeUpdateEntities(mutationModel, node.where, proceed);
851
+ }
852
+ const result = await proceed(this.transformNode(node));
853
+ if (hasPostUpdatePolicies && result.rows.length > 0) {
854
+ if (beforeUpdateInfo) {
855
+ (0, import_common_helpers3.invariant)(beforeUpdateInfo.rows.length === result.rows.length);
856
+ const idFields = import_runtime7.QueryUtils.requireIdFields(this.client.$schema, mutationModel);
857
+ for (const postRow of result.rows) {
858
+ const beforeRow = beforeUpdateInfo.rows.find((r) => idFields.every((f) => r[f] === postRow[f]));
859
+ if (!beforeRow) {
860
+ throw new import_runtime7.QueryError("Before-update and after-update rows do not match by id. If you have post-update policies on a model, updating id fields is not supported.");
861
+ }
862
+ }
863
+ }
864
+ const idConditions = this.buildIdConditions(mutationModel, result.rows);
865
+ const postUpdateFilter = this.buildPolicyFilter(mutationModel, void 0, "post-update");
866
+ const eb = (0, import_kysely3.expressionBuilder)();
867
+ const beforeUpdateTable = beforeUpdateInfo ? {
868
+ kind: "SelectQueryNode",
869
+ from: import_kysely3.FromNode.create([
870
+ import_kysely3.ParensNode.create(import_kysely3.ValuesNode.create(beforeUpdateInfo.rows.map((r) => import_kysely3.PrimitiveValueListNode.create(beforeUpdateInfo.fields.map((f) => r[f])))))
871
+ ]),
872
+ selections: beforeUpdateInfo.fields.map((name, index) => {
873
+ const def = import_runtime7.QueryUtils.requireField(this.client.$schema, mutationModel, name);
874
+ const castedColumnRef = import_kysely3.sql`CAST(${eb.ref(`column${index + 1}`)} as ${import_kysely3.sql.raw(this.dialect.getFieldSqlType(def))})`.as(name);
875
+ return import_kysely3.SelectionNode.create(castedColumnRef.toOperationNode());
876
+ })
877
+ } : void 0;
878
+ const postUpdateQuery = eb.selectFrom(mutationModel).select(() => [
879
+ eb(eb.fn("COUNT", [
880
+ eb.lit(1)
881
+ ]), "=", result.rows.length).as("$condition")
882
+ ]).where(() => new import_kysely3.ExpressionWrapper(conjunction(this.dialect, [
883
+ idConditions,
884
+ postUpdateFilter
885
+ ]))).$if(!!beforeUpdateInfo, (qb) => qb.leftJoin(() => new import_kysely3.ExpressionWrapper(beforeUpdateTable).as("$before"), (join) => {
886
+ const idFields = import_runtime7.QueryUtils.requireIdFields(this.client.$schema, mutationModel);
887
+ return idFields.reduce((acc, f) => acc.onRef(`${mutationModel}.${f}`, "=", `$before.${f}`), join);
888
+ }));
889
+ const postUpdateResult = await proceed(postUpdateQuery.toOperationNode());
890
+ if (!postUpdateResult.rows[0]?.$condition) {
891
+ throw new import_runtime7.RejectedByPolicyError(mutationModel, import_runtime7.RejectedByPolicyReason.NO_ACCESS, "some or all updated rows failed to pass post-update policy check");
892
+ }
893
+ }
894
+ if (!node.returning || this.onlyReturningId(node)) {
895
+ return this.postProcessMutationResult(result, node);
896
+ } else {
897
+ const readBackResult = await this.processReadBack(node, result, proceed);
898
+ if (readBackResult.rows.length !== result.rows.length) {
899
+ throw new import_runtime7.RejectedByPolicyError(mutationModel, import_runtime7.RejectedByPolicyReason.CANNOT_READ_BACK, "result is not allowed to be read back");
900
+ }
901
+ return readBackResult;
902
+ }
903
+ }
904
+ // correction to kysely mutation result may be needed because we might have added
905
+ // returning clause to the query and caused changes to the result shape
906
+ postProcessMutationResult(result, node) {
907
+ if (node.returning) {
908
+ return result;
909
+ } else {
910
+ return {
911
+ ...result,
912
+ rows: [],
913
+ numAffectedRows: result.numAffectedRows ?? BigInt(result.rows.length)
914
+ };
915
+ }
916
+ }
917
+ hasPostUpdatePolicies(model) {
918
+ const policies = this.getModelPolicies(model, "post-update");
919
+ return policies.length > 0;
920
+ }
921
+ async loadBeforeUpdateEntities(model, where, proceed) {
922
+ const beforeUpdateAccessFields = this.getFieldsAccessForBeforeUpdatePolicies(model);
923
+ if (!beforeUpdateAccessFields || beforeUpdateAccessFields.length === 0) {
924
+ return void 0;
925
+ }
926
+ const policyFilter = this.buildPolicyFilter(model, model, "update");
927
+ const combinedFilter = where ? conjunction(this.dialect, [
928
+ where.where,
929
+ policyFilter
930
+ ]) : policyFilter;
931
+ const query = {
932
+ kind: "SelectQueryNode",
933
+ from: import_kysely3.FromNode.create([
934
+ import_kysely3.TableNode.create(model)
935
+ ]),
936
+ where: import_kysely3.WhereNode.create(combinedFilter),
937
+ selections: [
938
+ ...beforeUpdateAccessFields.map((f) => import_kysely3.SelectionNode.create(import_kysely3.ColumnNode.create(f)))
939
+ ]
940
+ };
941
+ const result = await proceed(query);
942
+ return {
943
+ fields: beforeUpdateAccessFields,
944
+ rows: result.rows
945
+ };
946
+ }
947
+ getFieldsAccessForBeforeUpdatePolicies(model) {
948
+ const policies = this.getModelPolicies(model, "post-update");
949
+ if (policies.length === 0) {
950
+ return void 0;
951
+ }
952
+ const fields = /* @__PURE__ */ new Set();
953
+ const fieldCollector = new class extends import_runtime7.SchemaUtils.ExpressionVisitor {
954
+ visitMember(e) {
955
+ if (isBeforeInvocation(e.receiver)) {
956
+ (0, import_common_helpers3.invariant)(e.members.length === 1, "before() can only be followed by a scalar field access");
957
+ fields.add(e.members[0]);
958
+ }
959
+ super.visitMember(e);
960
+ }
961
+ }();
962
+ for (const policy of policies) {
963
+ fieldCollector.visit(policy.condition);
964
+ }
965
+ if (fields.size === 0) {
966
+ return void 0;
967
+ }
968
+ import_runtime7.QueryUtils.requireIdFields(this.client.$schema, model).forEach((f) => fields.add(f));
969
+ return Array.from(fields).sort();
970
+ }
971
+ // #region overrides
972
+ transformSelectQuery(node) {
973
+ if (!node.from) {
974
+ return super.transformSelectQuery(node);
975
+ }
976
+ let whereNode = this.transformNode(node.where);
977
+ const policyFilter = this.createPolicyFilterForFrom(node.from);
978
+ if (policyFilter) {
979
+ whereNode = import_kysely3.WhereNode.create(whereNode?.where ? conjunction(this.dialect, [
980
+ whereNode.where,
981
+ policyFilter
982
+ ]) : policyFilter);
983
+ }
984
+ const baseResult = super.transformSelectQuery({
985
+ ...node,
986
+ where: void 0
987
+ });
988
+ return {
989
+ ...baseResult,
990
+ where: whereNode
991
+ };
992
+ }
993
+ transformJoin(node) {
994
+ const table = this.extractTableName(node.table);
995
+ if (!table) {
996
+ return super.transformJoin(node);
997
+ }
998
+ const filter = this.buildPolicyFilter(table.model, table.alias, "read");
999
+ const nestedSelect = {
1000
+ kind: "SelectQueryNode",
1001
+ from: import_kysely3.FromNode.create([
1002
+ node.table
1003
+ ]),
1004
+ selections: [
1005
+ import_kysely3.SelectionNode.createSelectAll()
1006
+ ],
1007
+ where: import_kysely3.WhereNode.create(filter)
1008
+ };
1009
+ return {
1010
+ ...node,
1011
+ table: import_kysely3.AliasNode.create(import_kysely3.ParensNode.create(nestedSelect), import_kysely3.IdentifierNode.create(table.alias ?? table.model))
1012
+ };
1013
+ }
1014
+ transformInsertQuery(node) {
1015
+ let onConflict = node.onConflict;
1016
+ if (onConflict?.updates) {
1017
+ const { mutationModel, alias } = this.getMutationModel(node);
1018
+ const filter = this.buildPolicyFilter(mutationModel, alias, "update");
1019
+ if (onConflict.updateWhere) {
1020
+ onConflict = {
1021
+ ...onConflict,
1022
+ updateWhere: import_kysely3.WhereNode.create(conjunction(this.dialect, [
1023
+ onConflict.updateWhere.where,
1024
+ filter
1025
+ ]))
1026
+ };
1027
+ } else {
1028
+ onConflict = {
1029
+ ...onConflict,
1030
+ updateWhere: import_kysely3.WhereNode.create(filter)
1031
+ };
1032
+ }
1033
+ }
1034
+ const processedNode = onConflict ? {
1035
+ ...node,
1036
+ onConflict
1037
+ } : node;
1038
+ const result = super.transformInsertQuery(processedNode);
1039
+ let returning = result.returning;
1040
+ if (returning) {
1041
+ const { mutationModel } = this.getMutationModel(node);
1042
+ const idFields = import_runtime7.QueryUtils.requireIdFields(this.client.$schema, mutationModel);
1043
+ returning = import_kysely3.ReturningNode.create(idFields.map((f) => import_kysely3.SelectionNode.create(import_kysely3.ColumnNode.create(f))));
1044
+ }
1045
+ return {
1046
+ ...result,
1047
+ returning
1048
+ };
1049
+ }
1050
+ transformUpdateQuery(node) {
1051
+ const result = super.transformUpdateQuery(node);
1052
+ const { mutationModel, alias } = this.getMutationModel(node);
1053
+ let filter = this.buildPolicyFilter(mutationModel, alias, "update");
1054
+ if (node.from) {
1055
+ const joinFilter = this.createPolicyFilterForFrom(node.from);
1056
+ if (joinFilter) {
1057
+ filter = conjunction(this.dialect, [
1058
+ filter,
1059
+ joinFilter
1060
+ ]);
1061
+ }
1062
+ }
1063
+ let returning = result.returning;
1064
+ if (returning || this.hasPostUpdatePolicies(mutationModel)) {
1065
+ const idFields = import_runtime7.QueryUtils.requireIdFields(this.client.$schema, mutationModel);
1066
+ returning = import_kysely3.ReturningNode.create(idFields.map((f) => import_kysely3.SelectionNode.create(import_kysely3.ColumnNode.create(f))));
1067
+ }
1068
+ return {
1069
+ ...result,
1070
+ where: import_kysely3.WhereNode.create(result.where ? conjunction(this.dialect, [
1071
+ result.where.where,
1072
+ filter
1073
+ ]) : filter),
1074
+ returning
1075
+ };
1076
+ }
1077
+ transformDeleteQuery(node) {
1078
+ const result = super.transformDeleteQuery(node);
1079
+ const { mutationModel, alias } = this.getMutationModel(node);
1080
+ let filter = this.buildPolicyFilter(mutationModel, alias, "delete");
1081
+ if (node.using) {
1082
+ const joinFilter = this.createPolicyFilterForTables(node.using.tables);
1083
+ if (joinFilter) {
1084
+ filter = conjunction(this.dialect, [
1085
+ filter,
1086
+ joinFilter
1087
+ ]);
1088
+ }
1089
+ }
1090
+ return {
1091
+ ...result,
1092
+ where: import_kysely3.WhereNode.create(result.where ? conjunction(this.dialect, [
1093
+ result.where.where,
1094
+ filter
1095
+ ]) : filter)
1096
+ };
1097
+ }
1098
+ // #endregion
1099
+ // #region helpers
1100
+ onlyReturningId(node) {
1101
+ if (!node.returning) {
1102
+ return true;
1103
+ }
1104
+ const { mutationModel } = this.getMutationModel(node);
1105
+ const idFields = import_runtime7.QueryUtils.requireIdFields(this.client.$schema, mutationModel);
1106
+ if (node.returning.selections.some((s) => import_kysely3.SelectAllNode.is(s.selection))) {
1107
+ const modelDef = import_runtime7.QueryUtils.requireModel(this.client.$schema, mutationModel);
1108
+ if (Object.keys(modelDef.fields).some((f) => !idFields.includes(f))) {
1109
+ return false;
1110
+ } else {
1111
+ return true;
1112
+ }
1113
+ }
1114
+ const collector = new ColumnCollector();
1115
+ const selectedColumns = collector.collect(node.returning);
1116
+ return selectedColumns.every((c) => idFields.includes(c));
1117
+ }
1118
+ async enforcePreCreatePolicy(node, mutationModel, isManyToManyJoinTable, proceed) {
1119
+ const fields = node.columns?.map((c) => c.column.name) ?? [];
1120
+ const valueRows = node.values ? this.unwrapCreateValueRows(node.values, mutationModel, fields, isManyToManyJoinTable) : [
1121
+ []
1122
+ ];
1123
+ for (const values of valueRows) {
1124
+ if (isManyToManyJoinTable) {
1125
+ await this.enforcePreCreatePolicyForManyToManyJoinTable(mutationModel, fields, values.map((v) => v.node), proceed);
1126
+ } else {
1127
+ await this.enforcePreCreatePolicyForOne(mutationModel, fields, values.map((v) => v.node), proceed);
1128
+ }
1129
+ }
1130
+ }
1131
+ async enforcePreCreatePolicyForManyToManyJoinTable(tableName, fields, values, proceed) {
1132
+ const m2m = this.resolveManyToManyJoinTable(tableName);
1133
+ (0, import_common_helpers3.invariant)(m2m);
1134
+ (0, import_common_helpers3.invariant)(fields.includes("A") && fields.includes("B"), "many-to-many join table must have A and B fk fields");
1135
+ const aIndex = fields.indexOf("A");
1136
+ const aNode = values[aIndex];
1137
+ const bIndex = fields.indexOf("B");
1138
+ const bNode = values[bIndex];
1139
+ (0, import_common_helpers3.invariant)(import_kysely3.ValueNode.is(aNode) && import_kysely3.ValueNode.is(bNode), "A and B values must be ValueNode");
1140
+ const aValue = aNode.value;
1141
+ const bValue = bNode.value;
1142
+ (0, import_common_helpers3.invariant)(aValue !== null && aValue !== void 0, "A value cannot be null or undefined");
1143
+ (0, import_common_helpers3.invariant)(bValue !== null && bValue !== void 0, "B value cannot be null or undefined");
1144
+ const eb = (0, import_kysely3.expressionBuilder)();
1145
+ const filterA = this.buildPolicyFilter(m2m.firstModel, void 0, "update");
1146
+ const queryA = eb.selectFrom(m2m.firstModel).where(eb(eb.ref(`${m2m.firstModel}.${m2m.firstIdField}`), "=", aValue)).select(() => new import_kysely3.ExpressionWrapper(filterA).as("$t"));
1147
+ const filterB = this.buildPolicyFilter(m2m.secondModel, void 0, "update");
1148
+ const queryB = eb.selectFrom(m2m.secondModel).where(eb(eb.ref(`${m2m.secondModel}.${m2m.secondIdField}`), "=", bValue)).select(() => new import_kysely3.ExpressionWrapper(filterB).as("$t"));
1149
+ const queryNode = {
1150
+ kind: "SelectQueryNode",
1151
+ selections: [
1152
+ import_kysely3.SelectionNode.create(import_kysely3.AliasNode.create(queryA.toOperationNode(), import_kysely3.IdentifierNode.create("$conditionA"))),
1153
+ import_kysely3.SelectionNode.create(import_kysely3.AliasNode.create(queryB.toOperationNode(), import_kysely3.IdentifierNode.create("$conditionB")))
1154
+ ]
1155
+ };
1156
+ const result = await proceed(queryNode);
1157
+ if (!result.rows[0]?.$conditionA) {
1158
+ throw new import_runtime7.RejectedByPolicyError(m2m.firstModel, import_runtime7.RejectedByPolicyReason.CANNOT_READ_BACK, `many-to-many relation participant model "${m2m.firstModel}" not updatable`);
1159
+ }
1160
+ if (!result.rows[0]?.$conditionB) {
1161
+ throw new import_runtime7.RejectedByPolicyError(m2m.secondModel, import_runtime7.RejectedByPolicyReason.NO_ACCESS, `many-to-many relation participant model "${m2m.secondModel}" not updatable`);
1162
+ }
1163
+ }
1164
+ async enforcePreCreatePolicyForOne(model, fields, values, proceed) {
1165
+ const allFields = Object.entries(import_runtime7.QueryUtils.requireModel(this.client.$schema, model).fields).filter(([, def]) => !def.relation);
1166
+ const allValues = [];
1167
+ for (const [name, _def] of allFields) {
1168
+ const index = fields.indexOf(name);
1169
+ if (index >= 0) {
1170
+ allValues.push(values[index]);
1171
+ } else {
1172
+ allValues.push(import_kysely3.ValueNode.createImmediate(null));
1173
+ }
1174
+ }
1175
+ const eb = (0, import_kysely3.expressionBuilder)();
1176
+ const constTable = {
1177
+ kind: "SelectQueryNode",
1178
+ from: import_kysely3.FromNode.create([
1179
+ import_kysely3.AliasNode.create(import_kysely3.ParensNode.create(import_kysely3.ValuesNode.create([
1180
+ import_kysely3.ValueListNode.create(allValues)
1181
+ ])), import_kysely3.IdentifierNode.create("$t"))
1182
+ ]),
1183
+ selections: allFields.map(([name, def], index) => {
1184
+ const castedColumnRef = import_kysely3.sql`CAST(${eb.ref(`column${index + 1}`)} as ${import_kysely3.sql.raw(this.dialect.getFieldSqlType(def))})`.as(name);
1185
+ return import_kysely3.SelectionNode.create(castedColumnRef.toOperationNode());
1186
+ })
1187
+ };
1188
+ const filter = this.buildPolicyFilter(model, void 0, "create");
1189
+ const preCreateCheck = {
1190
+ kind: "SelectQueryNode",
1191
+ from: import_kysely3.FromNode.create([
1192
+ import_kysely3.AliasNode.create(constTable, import_kysely3.IdentifierNode.create(model))
1193
+ ]),
1194
+ selections: [
1195
+ import_kysely3.SelectionNode.create(import_kysely3.AliasNode.create(import_kysely3.BinaryOperationNode.create(import_kysely3.FunctionNode.create("COUNT", [
1196
+ import_kysely3.ValueNode.createImmediate(1)
1197
+ ]), import_kysely3.OperatorNode.create(">"), import_kysely3.ValueNode.createImmediate(0)), import_kysely3.IdentifierNode.create("$condition")))
1198
+ ],
1199
+ where: import_kysely3.WhereNode.create(filter)
1200
+ };
1201
+ const result = await proceed(preCreateCheck);
1202
+ if (!result.rows[0]?.$condition) {
1203
+ throw new import_runtime7.RejectedByPolicyError(model);
1204
+ }
1205
+ }
1206
+ unwrapCreateValueRows(node, model, fields, isManyToManyJoinTable) {
1207
+ if (import_kysely3.ValuesNode.is(node)) {
1208
+ return node.values.map((v) => this.unwrapCreateValueRow(v.values, model, fields, isManyToManyJoinTable));
1209
+ } else if (import_kysely3.PrimitiveValueListNode.is(node)) {
1210
+ return [
1211
+ this.unwrapCreateValueRow(node.values, model, fields, isManyToManyJoinTable)
1212
+ ];
1213
+ } else {
1214
+ throw new import_runtime7.InternalError(`Unexpected node kind: ${node.kind} for unwrapping create values`);
1215
+ }
1216
+ }
1217
+ unwrapCreateValueRow(data, model, fields, isImplicitManyToManyJoinTable) {
1218
+ (0, import_common_helpers3.invariant)(data.length === fields.length, "data length must match fields length");
1219
+ const result = [];
1220
+ for (let i = 0; i < data.length; i++) {
1221
+ const item = data[i];
1222
+ if (typeof item === "object" && item && "kind" in item) {
1223
+ const fieldDef = import_runtime7.QueryUtils.requireField(this.client.$schema, model, fields[i]);
1224
+ (0, import_common_helpers3.invariant)(item.kind === "ValueNode", "expecting a ValueNode");
1225
+ result.push({
1226
+ node: import_kysely3.ValueNode.create(this.dialect.transformPrimitive(item.value, fieldDef.type, !!fieldDef.array)),
1227
+ raw: item.value
1228
+ });
1229
+ } else {
1230
+ let value = item;
1231
+ if (!isImplicitManyToManyJoinTable) {
1232
+ const fieldDef = import_runtime7.QueryUtils.requireField(this.client.$schema, model, fields[i]);
1233
+ value = this.dialect.transformPrimitive(item, fieldDef.type, !!fieldDef.array);
1234
+ }
1235
+ if (Array.isArray(value)) {
1236
+ result.push({
1237
+ node: import_kysely3.RawNode.createWithSql(this.dialect.buildArrayLiteralSQL(value)),
1238
+ raw: value
1239
+ });
1240
+ } else {
1241
+ result.push({
1242
+ node: import_kysely3.ValueNode.create(value),
1243
+ raw: value
1244
+ });
1245
+ }
1246
+ }
1247
+ }
1248
+ return result;
1249
+ }
1250
+ tryGetConstantPolicy(model, operation) {
1251
+ const policies = this.getModelPolicies(model, operation);
1252
+ if (!policies.some((p) => p.kind === "allow")) {
1253
+ return false;
1254
+ } else if (
1255
+ // unconditional deny
1256
+ policies.some((p) => p.kind === "deny" && this.isTrueExpr(p.condition))
1257
+ ) {
1258
+ return false;
1259
+ } else if (
1260
+ // unconditional allow
1261
+ !policies.some((p) => p.kind === "deny") && policies.some((p) => p.kind === "allow" && this.isTrueExpr(p.condition))
1262
+ ) {
1263
+ return true;
1264
+ } else {
1265
+ return void 0;
1266
+ }
1267
+ }
1268
+ isTrueExpr(expr2) {
1269
+ return import_schema4.ExpressionUtils.isLiteral(expr2) && expr2.value === true;
1270
+ }
1271
+ async processReadBack(node, result, proceed) {
1272
+ if (result.rows.length === 0) {
1273
+ return result;
1274
+ }
1275
+ if (!this.isMutationQueryNode(node) || !node.returning) {
1276
+ return result;
1277
+ }
1278
+ const { mutationModel } = this.getMutationModel(node);
1279
+ const idConditions = this.buildIdConditions(mutationModel, result.rows);
1280
+ const policyFilter = this.buildPolicyFilter(mutationModel, void 0, "read");
1281
+ const select = {
1282
+ kind: "SelectQueryNode",
1283
+ from: import_kysely3.FromNode.create([
1284
+ import_kysely3.TableNode.create(mutationModel)
1285
+ ]),
1286
+ where: import_kysely3.WhereNode.create(conjunction(this.dialect, [
1287
+ idConditions,
1288
+ policyFilter
1289
+ ])),
1290
+ selections: node.returning.selections
1291
+ };
1292
+ const selectResult = await proceed(select);
1293
+ return selectResult;
1294
+ }
1295
+ buildIdConditions(table, rows) {
1296
+ const idFields = import_runtime7.QueryUtils.requireIdFields(this.client.$schema, table);
1297
+ return disjunction(this.dialect, rows.map((row) => conjunction(this.dialect, idFields.map((field) => import_kysely3.BinaryOperationNode.create(import_kysely3.ReferenceNode.create(import_kysely3.ColumnNode.create(field), import_kysely3.TableNode.create(table)), import_kysely3.OperatorNode.create("="), import_kysely3.ValueNode.create(row[field]))))));
1298
+ }
1299
+ getMutationModel(node) {
1300
+ const r = (0, import_ts_pattern3.match)(node).when(import_kysely3.InsertQueryNode.is, (node2) => ({
1301
+ mutationModel: getTableName(node2.into),
1302
+ alias: void 0
1303
+ })).when(import_kysely3.UpdateQueryNode.is, (node2) => {
1304
+ if (!node2.table) {
1305
+ throw new import_runtime7.QueryError("Update query must have a table");
1306
+ }
1307
+ const r2 = this.extractTableName(node2.table);
1308
+ return r2 ? {
1309
+ mutationModel: r2.model,
1310
+ alias: r2.alias
1311
+ } : void 0;
1312
+ }).when(import_kysely3.DeleteQueryNode.is, (node2) => {
1313
+ if (node2.from.froms.length !== 1) {
1314
+ throw new import_runtime7.QueryError("Only one from table is supported for delete");
1315
+ }
1316
+ const r2 = this.extractTableName(node2.from.froms[0]);
1317
+ return r2 ? {
1318
+ mutationModel: r2.model,
1319
+ alias: r2.alias
1320
+ } : void 0;
1321
+ }).exhaustive();
1322
+ if (!r) {
1323
+ throw new import_runtime7.InternalError(`Unable to get table name for query node: ${node}`);
1324
+ }
1325
+ return r;
1326
+ }
1327
+ isCrudQueryNode(node) {
1328
+ return import_kysely3.SelectQueryNode.is(node) || import_kysely3.InsertQueryNode.is(node) || import_kysely3.UpdateQueryNode.is(node) || import_kysely3.DeleteQueryNode.is(node);
1329
+ }
1330
+ isMutationQueryNode(node) {
1331
+ return import_kysely3.InsertQueryNode.is(node) || import_kysely3.UpdateQueryNode.is(node) || import_kysely3.DeleteQueryNode.is(node);
1332
+ }
1333
+ buildPolicyFilter(model, alias, operation) {
1334
+ const m2mFilter = this.getModelPolicyFilterForManyToManyJoinTable(model, alias, operation);
1335
+ if (m2mFilter) {
1336
+ return m2mFilter;
1337
+ }
1338
+ const policies = this.getModelPolicies(model, operation);
1339
+ const allows = policies.filter((policy) => policy.kind === "allow").map((policy) => this.compilePolicyCondition(model, alias, operation, policy));
1340
+ const denies = policies.filter((policy) => policy.kind === "deny").map((policy) => this.compilePolicyCondition(model, alias, operation, policy));
1341
+ let combinedPolicy;
1342
+ if (allows.length === 0) {
1343
+ if (operation === "post-update") {
1344
+ combinedPolicy = trueNode(this.dialect);
1345
+ } else {
1346
+ combinedPolicy = falseNode(this.dialect);
1347
+ }
1348
+ } else {
1349
+ combinedPolicy = disjunction(this.dialect, allows);
1350
+ }
1351
+ if (denies.length !== 0) {
1352
+ const combinedDenies = conjunction(this.dialect, denies.map((d) => buildIsFalse(d, this.dialect)));
1353
+ combinedPolicy = conjunction(this.dialect, [
1354
+ combinedPolicy,
1355
+ combinedDenies
1356
+ ]);
1357
+ }
1358
+ return combinedPolicy;
1359
+ }
1360
+ extractTableName(node) {
1361
+ if (import_kysely3.TableNode.is(node)) {
1362
+ return {
1363
+ model: node.table.identifier.name
1364
+ };
1365
+ }
1366
+ if (import_kysely3.AliasNode.is(node)) {
1367
+ const inner = this.extractTableName(node.node);
1368
+ if (!inner) {
1369
+ return void 0;
1370
+ }
1371
+ return {
1372
+ model: inner.model,
1373
+ alias: import_kysely3.IdentifierNode.is(node.alias) ? node.alias.name : void 0
1374
+ };
1375
+ } else {
1376
+ return void 0;
1377
+ }
1378
+ }
1379
+ createPolicyFilterForFrom(node) {
1380
+ if (!node) {
1381
+ return void 0;
1382
+ }
1383
+ return this.createPolicyFilterForTables(node.froms);
1384
+ }
1385
+ createPolicyFilterForTables(tables) {
1386
+ return tables.reduce((acc, table) => {
1387
+ const extractResult = this.extractTableName(table);
1388
+ if (extractResult) {
1389
+ const { model, alias } = extractResult;
1390
+ const filter = this.buildPolicyFilter(model, alias, "read");
1391
+ return acc ? conjunction(this.dialect, [
1392
+ acc,
1393
+ filter
1394
+ ]) : filter;
1395
+ }
1396
+ return acc;
1397
+ }, void 0);
1398
+ }
1399
+ compilePolicyCondition(model, alias, operation, policy) {
1400
+ return new ExpressionTransformer(this.client).transform(policy.condition, {
1401
+ model,
1402
+ alias,
1403
+ operation
1404
+ });
1405
+ }
1406
+ getModelPolicies(model, operation) {
1407
+ const modelDef = import_runtime7.QueryUtils.requireModel(this.client.$schema, model);
1408
+ const result = [];
1409
+ const extractOperations = /* @__PURE__ */ __name((expr2) => {
1410
+ (0, import_common_helpers3.invariant)(import_schema4.ExpressionUtils.isLiteral(expr2), "expecting a literal");
1411
+ (0, import_common_helpers3.invariant)(typeof expr2.value === "string", "expecting a string literal");
1412
+ return expr2.value.split(",").filter((v) => !!v).map((v) => v.trim());
1413
+ }, "extractOperations");
1414
+ if (modelDef.attributes) {
1415
+ result.push(...modelDef.attributes.filter((attr) => attr.name === "@@allow" || attr.name === "@@deny").map((attr) => ({
1416
+ kind: attr.name === "@@allow" ? "allow" : "deny",
1417
+ operations: extractOperations(attr.args[0].value),
1418
+ condition: attr.args[1].value
1419
+ })).filter((policy) => operation !== "post-update" && policy.operations.includes("all") || policy.operations.includes(operation)));
1420
+ }
1421
+ return result;
1422
+ }
1423
+ resolveManyToManyJoinTable(tableName) {
1424
+ for (const model of Object.values(this.client.$schema.models)) {
1425
+ for (const field of Object.values(model.fields)) {
1426
+ const m2m = import_runtime7.QueryUtils.getManyToManyRelation(this.client.$schema, model.name, field.name);
1427
+ if (m2m?.joinTable === tableName) {
1428
+ const sortedRecord = [
1429
+ {
1430
+ model: model.name,
1431
+ field: field.name
1432
+ },
1433
+ {
1434
+ model: m2m.otherModel,
1435
+ field: m2m.otherField
1436
+ }
1437
+ ].sort(this.manyToManySorter);
1438
+ const firstIdFields = import_runtime7.QueryUtils.requireIdFields(this.client.$schema, sortedRecord[0].model);
1439
+ const secondIdFields = import_runtime7.QueryUtils.requireIdFields(this.client.$schema, sortedRecord[1].model);
1440
+ (0, import_common_helpers3.invariant)(firstIdFields.length === 1 && secondIdFields.length === 1, "only single-field id is supported for implicit many-to-many join table");
1441
+ return {
1442
+ firstModel: sortedRecord[0].model,
1443
+ firstField: sortedRecord[0].field,
1444
+ firstIdField: firstIdFields[0],
1445
+ secondModel: sortedRecord[1].model,
1446
+ secondField: sortedRecord[1].field,
1447
+ secondIdField: secondIdFields[0]
1448
+ };
1449
+ }
1450
+ }
1451
+ }
1452
+ return void 0;
1453
+ }
1454
+ manyToManySorter(a, b) {
1455
+ return a.model !== b.model ? a.model.localeCompare(b.model) : a.field.localeCompare(b.field);
1456
+ }
1457
+ isManyToManyJoinTable(tableName) {
1458
+ return !!this.resolveManyToManyJoinTable(tableName);
1459
+ }
1460
+ getModelPolicyFilterForManyToManyJoinTable(tableName, alias, operation) {
1461
+ const m2m = this.resolveManyToManyJoinTable(tableName);
1462
+ if (!m2m) {
1463
+ return void 0;
1464
+ }
1465
+ const checkForOperation = operation === "read" ? "read" : "update";
1466
+ const eb = (0, import_kysely3.expressionBuilder)();
1467
+ const joinTable = alias ?? tableName;
1468
+ const aQuery = eb.selectFrom(m2m.firstModel).whereRef(`${m2m.firstModel}.${m2m.firstIdField}`, "=", `${joinTable}.A`).select(() => new import_kysely3.ExpressionWrapper(this.buildPolicyFilter(m2m.firstModel, void 0, checkForOperation)).as("$conditionA"));
1469
+ const bQuery = eb.selectFrom(m2m.secondModel).whereRef(`${m2m.secondModel}.${m2m.secondIdField}`, "=", `${joinTable}.B`).select(() => new import_kysely3.ExpressionWrapper(this.buildPolicyFilter(m2m.secondModel, void 0, checkForOperation)).as("$conditionB"));
1470
+ return eb.and([
1471
+ aQuery,
1472
+ bQuery
1473
+ ]).toOperationNode();
1474
+ }
1475
+ };
1476
+
1477
+ // src/functions.ts
1478
+ var check = /* @__PURE__ */ __name((eb, args, { client, model, modelAlias, operation }) => {
1479
+ (0, import_common_helpers4.invariant)(args.length === 1 || args.length === 2, '"check" function requires 1 or 2 arguments');
1480
+ const arg1Node = args[0].toOperationNode();
1481
+ const arg2Node = args.length === 2 ? args[1].toOperationNode() : void 0;
1482
+ if (arg2Node) {
1483
+ (0, import_common_helpers4.invariant)(import_kysely4.ValueNode.is(arg2Node) && typeof arg2Node.value === "string", '"operation" parameter must be a string literal when provided');
1484
+ (0, import_common_helpers4.invariant)(import_runtime9.CRUD.includes(arg2Node.value), '"operation" parameter must be one of "create", "read", "update", "delete"');
1485
+ }
1486
+ const fieldName = import_runtime9.QueryUtils.extractFieldName(arg1Node);
1487
+ (0, import_common_helpers4.invariant)(fieldName, 'Failed to extract field name from the first argument of "check" function');
1488
+ const fieldDef = import_runtime9.QueryUtils.requireField(client.$schema, model, fieldName);
1489
+ (0, import_common_helpers4.invariant)(fieldDef.relation, `Field "${fieldName}" is not a relation field in model "${model}"`);
1490
+ (0, import_common_helpers4.invariant)(!fieldDef.array, `Field "${fieldName}" is a to-many relation, which is not supported by "check"`);
1491
+ const relationModel = fieldDef.type;
1492
+ const joinConditions = [];
1493
+ const fkInfo = import_runtime9.QueryUtils.getRelationForeignKeyFieldPairs(client.$schema, model, fieldName);
1494
+ const idFields = import_runtime9.QueryUtils.requireIdFields(client.$schema, model);
1495
+ const buildBaseSelect = /* @__PURE__ */ __name((baseModel, field) => {
1496
+ return eb.selectFrom(baseModel).select(field).where(eb.and(idFields.map((idField) => eb(eb.ref(`${fieldDef.originModel}.${idField}`), "=", eb.ref(`${modelAlias}.${idField}`)))));
1497
+ }, "buildBaseSelect");
1498
+ if (fkInfo.ownedByModel) {
1499
+ joinConditions.push(...fkInfo.keyPairs.map(({ fk, pk }) => {
1500
+ let fkRef;
1501
+ if (fieldDef.originModel && fieldDef.originModel !== model) {
1502
+ fkRef = buildBaseSelect(fieldDef.originModel, fk);
1503
+ } else {
1504
+ fkRef = eb.ref(`${modelAlias}.${fk}`);
1505
+ }
1506
+ return eb(fkRef, "=", eb.ref(`${relationModel}.${pk}`));
1507
+ }));
1508
+ } else {
1509
+ joinConditions.push(...fkInfo.keyPairs.map(({ fk, pk }) => {
1510
+ let pkRef;
1511
+ if (fieldDef.originModel && fieldDef.originModel !== model) {
1512
+ pkRef = buildBaseSelect(fieldDef.originModel, pk);
1513
+ } else {
1514
+ pkRef = eb.ref(`${modelAlias}.${pk}`);
1515
+ }
1516
+ return eb(pkRef, "=", eb.ref(`${relationModel}.${fk}`));
1517
+ }));
1518
+ }
1519
+ const joinCondition = joinConditions.length === 1 ? joinConditions[0] : eb.and(joinConditions);
1520
+ const policyHandler = new PolicyHandler(client);
1521
+ const op = arg2Node ? arg2Node.value : operation;
1522
+ const policyCondition = policyHandler.buildPolicyFilter(relationModel, void 0, op);
1523
+ const result = eb.selectFrom(relationModel).where(joinCondition).select(new import_kysely4.ExpressionWrapper(policyCondition).as("$condition"));
1524
+ return result;
1525
+ }, "check");
1526
+
1527
+ // src/plugin.ts
1528
+ var PolicyPlugin = class {
1529
+ static {
1530
+ __name(this, "PolicyPlugin");
1531
+ }
1532
+ get id() {
1533
+ return "policy";
1534
+ }
1535
+ get name() {
1536
+ return "Access Policy";
1537
+ }
1538
+ get description() {
1539
+ return "Enforces access policies defined in the schema.";
1540
+ }
1541
+ get functions() {
1542
+ return {
1543
+ check
1544
+ };
1545
+ }
1546
+ onKyselyQuery({ query, client, proceed }) {
1547
+ const handler = new PolicyHandler(client);
1548
+ return handler.handle(query, proceed);
1549
+ }
1550
+ };
1551
+ // Annotate the CommonJS export names for ESM import in node:
1552
+ 0 && (module.exports = {
1553
+ PolicyPlugin
1554
+ });
1555
+ //# sourceMappingURL=index.cjs.map