@zenstackhq/plugin-policy 3.9.8 → 3.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -192,6 +192,13 @@ function createRejectedByPolicyError(model, reason, message) {
192
192
  function createUnsupportedError(message) {
193
193
  return new _zenstackhq_orm.ORMError(_zenstackhq_orm.ORMErrorReason.NOT_SUPPORTED, message);
194
194
  }
195
+ /**
196
+ * Throws a config error if the given field is a parameterized computed field. Such fields need
197
+ * query-time args, which policy expressions have no way to provide.
198
+ */
199
+ function rejectParameterizedComputedField(fieldDef, model) {
200
+ if (fieldDef.computed && fieldDef.params) throw new _zenstackhq_orm.ORMError(_zenstackhq_orm.ORMErrorReason.CONFIG_ERROR, `Parameterized computed field "${fieldDef.name}" of model "${model}" cannot be used in a policy expression`);
201
+ }
195
202
  //#endregion
196
203
  //#region \0@oxc-project+runtime@0.124.0/helpers/decorateMetadata.js
197
204
  function __decorateMetadata(k, v) {
@@ -288,25 +295,34 @@ var ExpressionTransformer = class {
288
295
  if (op === "?" || op === "!" || op === "^") return this.transformCollectionPredicate(expr, context);
289
296
  const { normalizedLeft, normalizedRight } = this.normalizeBinaryOperationOperands(expr, context);
290
297
  const left = this.transform(normalizedLeft, context);
291
- const right = this.transform(normalizedRight, context);
292
298
  if (op === "in") if (this.isNullNode(left)) return this.transformValue(false, "Boolean");
293
- else if (kysely.ValueListNode.is(right)) return kysely.BinaryOperationNode.create(left, kysely.OperatorNode.create("in"), right);
294
299
  else {
295
- const leftFieldDef = this.getFieldDefFromFieldRef(normalizedLeft, context);
296
- const comparand = leftFieldDef && _zenstackhq_orm.QueryUtils.isEnum(this.schema, leftFieldDef.type) ? this.dialect.castText(new kysely.ExpressionWrapper(left)).toOperationNode() : left;
297
- if (kysely.SelectQueryNode.is(right)) {
298
- const rightFieldDef = this.getFieldDefFromFieldRef(normalizedRight, context);
299
- return this.dialect.buildArrayContains(new kysely.ExpressionWrapper(right), new kysely.ExpressionWrapper(comparand), rightFieldDef?.type).toOperationNode();
300
+ if (this.isLiteralArray(normalizedRight)) {
301
+ if (normalizedRight.items.length === 0) return this.transformValue(false, "Boolean");
302
+ return kysely.BinaryOperationNode.create(left, kysely.OperatorNode.create("in"), kysely.ValueListNode.create(normalizedRight.items.map((item) => this.transform(item, context))));
303
+ }
304
+ const right = this.transform(normalizedRight, context);
305
+ if (kysely.ValueListNode.is(right)) return kysely.BinaryOperationNode.create(left, kysely.OperatorNode.create("in"), right);
306
+ else {
307
+ const leftFieldDef = this.getFieldDefFromFieldRef(normalizedLeft, context);
308
+ const comparand = leftFieldDef && _zenstackhq_orm.QueryUtils.isEnum(this.schema, leftFieldDef.type) ? this.dialect.castText(new kysely.ExpressionWrapper(left)).toOperationNode() : left;
309
+ if (kysely.SelectQueryNode.is(right)) {
310
+ const rightFieldDef = this.getFieldDefFromFieldRef(normalizedRight, context);
311
+ return this.dialect.buildArrayContains(new kysely.ExpressionWrapper(right), new kysely.ExpressionWrapper(comparand), rightFieldDef?.type).toOperationNode();
312
+ }
313
+ return kysely.BinaryOperationNode.create(comparand, kysely.OperatorNode.create("="), kysely.FunctionNode.create("any", [right]));
300
314
  }
301
- return kysely.BinaryOperationNode.create(comparand, kysely.OperatorNode.create("="), kysely.FunctionNode.create("any", [right]));
302
315
  }
316
+ const right = this.transform(normalizedRight, context);
303
317
  if (this.isNullNode(right)) return this.transformNullCheck(left, expr.op);
304
318
  else if (this.isNullNode(left)) return this.transformNullCheck(right, expr.op);
305
319
  else {
306
320
  const leftFieldDef = this.getFieldDefFromFieldRef(normalizedLeft, context);
307
321
  const rightFieldDef = this.getFieldDefFromFieldRef(normalizedRight, context);
308
322
  const sqlOp = op === "==" ? "=" : op;
309
- return this.dialect.buildComparison(new kysely.ExpressionWrapper(left), leftFieldDef, sqlOp, new kysely.ExpressionWrapper(right), rightFieldDef).toOperationNode();
323
+ const asText = this.isBeforeEnumField(normalizedLeft, context) || this.isBeforeEnumField(normalizedRight, context);
324
+ const operand = (node) => asText ? this.dialect.castText(new kysely.ExpressionWrapper(node)) : new kysely.ExpressionWrapper(node);
325
+ return this.dialect.buildComparison(operand(left), leftFieldDef, sqlOp, operand(right), rightFieldDef).toOperationNode();
310
326
  }
311
327
  }
312
328
  transformNullCheck(expr, operator) {
@@ -315,6 +331,9 @@ var ExpressionTransformer = class {
315
331
  else return operator === "==" ? kysely.BinaryOperationNode.create(expr, kysely.OperatorNode.create("is"), kysely.ValueNode.createImmediate(null)) : kysely.BinaryOperationNode.create(expr, kysely.OperatorNode.create("is not"), kysely.ValueNode.createImmediate(null));
316
332
  else return kysely.ValueNode.createImmediate(null);
317
333
  }
334
+ isLiteralArray(expr) {
335
+ return expr.kind === "array" && expr.items.every((item) => item.kind === "literal");
336
+ }
318
337
  normalizeBinaryOperationOperands(expr, context) {
319
338
  let normalizedLeft = expr.left;
320
339
  if (this.isRelationField(expr.left, context)) {
@@ -662,8 +681,7 @@ var ExpressionTransformer = class {
662
681
  } else {
663
682
  (0, _zenstackhq_common_helpers.invariant)(i === members.length - 1, "plain field access must be the last segment");
664
683
  (0, _zenstackhq_common_helpers.invariant)(!currNode, "plain field access must be the last segment");
665
- if (fieldDef.originModel && fieldDef.originModel !== fromModel) currNode = this.buildDelegateBaseFieldSelect(fromModel, fromAlias, member, fieldDef.originModel);
666
- else currNode = kysely.ReferenceNode.create(kysely.ColumnNode.create(member), kysely.TableNode.create(fromAlias));
684
+ currNode = this.buildFieldRef(fromModel, member, fromAlias);
667
685
  }
668
686
  }
669
687
  return {
@@ -723,10 +741,18 @@ var ExpressionTransformer = class {
723
741
  return eb.selectFrom(`${m2m.otherModel} as ${relationAlias}`).innerJoin(`${m2m.joinTable} as ${joinTableAlias}`, (join) => join.onRef(`${relationAlias}.${m2m.otherPKName}`, "=", `${joinTableAlias}.${m2m.otherFkName}`).onRef(`${joinTableAlias}.${m2m.parentFkName}`, "=", `${context.alias ?? context.modelOrType}.${m2m.parentPKName}`)).toOperationNode();
724
742
  }
725
743
  createColumnRef(column, context) {
726
- const tableName = context.alias ?? context.modelOrType;
727
- const fieldDef = _zenstackhq_orm.QueryUtils.requireField(this.schema, context.modelOrType, column);
728
- if (!fieldDef.originModel || fieldDef.originModel === context.modelOrType) return kysely.ReferenceNode.create(kysely.ColumnNode.create(column), kysely.TableNode.create(tableName));
729
- return this.buildDelegateBaseFieldSelect(context.modelOrType, tableName, column, fieldDef.originModel);
744
+ return this.buildFieldRef(context.modelOrType, column, context.alias ?? context.modelOrType);
745
+ }
746
+ /**
747
+ * Builds a reference to a scalar field of `model` whose table is aliased as `modelAlias`.
748
+ * Handles regular columns, `@computed` fields (inlined via the dialect), and fields inherited
749
+ * from a delegate base model (looked up from the base table with a correlated subquery).
750
+ */
751
+ buildFieldRef(model, field, modelAlias) {
752
+ const fieldDef = _zenstackhq_orm.QueryUtils.requireField(this.schema, model, field);
753
+ rejectParameterizedComputedField(fieldDef, model);
754
+ if (!fieldDef.originModel || fieldDef.originModel === model) return fieldDef.computed ? this.dialect.fieldRef(model, field, modelAlias).toOperationNode() : kysely.ReferenceNode.create(kysely.ColumnNode.create(field), kysely.TableNode.create(modelAlias));
755
+ return this.buildDelegateBaseFieldSelect(model, modelAlias, field, fieldDef.originModel);
730
756
  }
731
757
  getEvaluationBindingScope(scope) {
732
758
  if (!scope) return;
@@ -739,7 +765,7 @@ var ExpressionTransformer = class {
739
765
  return {
740
766
  kind: "SelectQueryNode",
741
767
  from: kysely.FromNode.create([kysely.TableNode.create(baseModel)]),
742
- selections: [kysely.SelectionNode.create(kysely.ReferenceNode.create(kysely.ColumnNode.create(field), kysely.TableNode.create(baseModel)))],
768
+ selections: [kysely.SelectionNode.create(this.buildFieldRef(baseModel, field, baseModel))],
743
769
  where: kysely.WhereNode.create(conjunction(this.dialect, idFields.map((idField) => kysely.BinaryOperationNode.create(kysely.ReferenceNode.create(kysely.ColumnNode.create(idField), kysely.TableNode.create(baseModel)), kysely.OperatorNode.create("="), kysely.ReferenceNode.create(kysely.ColumnNode.create(idField), kysely.TableNode.create(modelAlias))))))
744
770
  };
745
771
  }
@@ -766,6 +792,11 @@ var ExpressionTransformer = class {
766
792
  isRelationField(expr, context) {
767
793
  return !!this.getFieldDefFromFieldRef(expr, context)?.relation;
768
794
  }
795
+ isBeforeEnumField(expr, context) {
796
+ if (!_zenstackhq_orm_schema.ExpressionUtils.isMember(expr) || !isBeforeInvocation(expr.receiver)) return false;
797
+ const fieldDef = _zenstackhq_orm.QueryUtils.getField(this.schema, context.thisType, expr.members[0]);
798
+ return !!fieldDef && _zenstackhq_orm.QueryUtils.isEnum(this.schema, fieldDef.type);
799
+ }
769
800
  getFieldDefFromFieldRef(expr, context) {
770
801
  return this.resolveFieldRef(expr, context)?.fieldDef;
771
802
  }
@@ -911,40 +942,59 @@ var PolicyHandler = class extends kysely.OperationNodeTransformer {
911
942
  const sides = [{
912
943
  column: "A",
913
944
  model: m2m.firstModel,
945
+ field: m2m.firstField,
914
946
  idField: m2m.firstIdField
915
947
  }, {
916
948
  column: "B",
917
949
  model: m2m.secondModel,
950
+ field: m2m.secondField,
918
951
  idField: m2m.secondIdField
919
952
  }].map((side) => ({
920
953
  ...side,
921
- value: this.extractEqualityValue(node.where?.where, side.column)
922
- })).filter((side) => side.value !== void 0);
954
+ values: this.extractConstrainedValues(node.where?.where, side.column)
955
+ })).filter((side) => side.values !== void 0);
923
956
  if (sides.length === 0) return;
924
957
  const result = await proceed({
925
958
  kind: "SelectQueryNode",
926
- selections: sides.map((side, index) => kysely.SelectionNode.create(kysely.AliasNode.create(this.eb.selectFrom(side.model).where(this.eb(this.eb.ref(`${side.model}.${side.idField}`), "=", side.value)).select(() => new kysely.ExpressionWrapper(this.buildPolicyFilter(side.model, void 0, "update")).as("_")).toOperationNode(), kysely.IdentifierNode.create(`$condition${index}`))))
959
+ selections: sides.map((side, index) => kysely.SelectionNode.create(kysely.AliasNode.create(this.eb.selectFrom(side.model).where(this.eb(this.eb.ref(`${side.model}.${side.idField}`), "in", side.values)).where(() => new kysely.ExpressionWrapper(this.buildM2mSidePolicyFilter(side.model, side.field))).select((eb) => eb.fn("COUNT", [eb.lit(1)]).as("_")).toOperationNode(), kysely.IdentifierNode.create(`$condition${index}`))))
927
960
  });
928
- for (const [index, side] of sides.entries()) if (!result.rows[0]?.[`$condition${index}`]) throw createRejectedByPolicyError(side.model, _zenstackhq_orm.RejectedByPolicyReason.NO_ACCESS, `many-to-many relation participant model "${side.model}" not updatable`);
961
+ for (const [index, side] of sides.entries()) {
962
+ const distinctValues = new Set(side.values).size;
963
+ if (Number(result.rows[0]?.[`$condition${index}`] ?? 0) < distinctValues) throw createRejectedByPolicyError(side.model, _zenstackhq_orm.RejectedByPolicyReason.NO_ACCESS, `many-to-many relation participant model "${side.model}" not updatable`);
964
+ }
929
965
  }
930
966
  /**
931
- * Finds the literal value that `column` is constrained to by a top-level conjunction of the given
932
- * where clause, or `undefined` if there's no such constraint.
967
+ * Finds the literal values that `column` is constrained to by a top-level conjunction of the
968
+ * given where clause, or `undefined` if there's no such constraint. Supports both `=` and `IN`
969
+ * operators.
933
970
  *
934
- * E.g., given the where clause `("A" = 1 AND "B" IN (2, 3))`, extracting column "A" returns `1`,
935
- * while extracting column "B" returns `undefined` since it's not an equality constraint.
971
+ * E.g., given the where clause `("A" = 1 AND "B" IN (2, 3))`, extracting column "A" returns
972
+ * `[1]`, and extracting column "B" returns `[2, 3]`.
936
973
  */
937
- extractEqualityValue(node, column) {
974
+ extractConstrainedValues(node, column) {
938
975
  if (!node) return;
939
- if (kysely.ParensNode.is(node)) return this.extractEqualityValue(node.node, column);
940
- if (kysely.AndNode.is(node)) return this.extractEqualityValue(node.left, column) ?? this.extractEqualityValue(node.right, column);
976
+ if (kysely.ParensNode.is(node)) return this.extractConstrainedValues(node.node, column);
977
+ if (kysely.AndNode.is(node)) return this.extractConstrainedValues(node.left, column) ?? this.extractConstrainedValues(node.right, column);
941
978
  if (!kysely.BinaryOperationNode.is(node)) return;
942
- if (!kysely.OperatorNode.is(node.operator) || node.operator.operator !== "=") return;
979
+ if (!kysely.OperatorNode.is(node.operator)) return;
943
980
  const { leftOperand, rightOperand } = node;
944
981
  if (!kysely.ReferenceNode.is(leftOperand) || !kysely.ColumnNode.is(leftOperand.column)) return;
945
982
  if (leftOperand.column.column.name !== column) return;
946
- if (!kysely.ValueNode.is(rightOperand) || rightOperand.value === null || rightOperand.value === void 0) return;
947
- return rightOperand.value;
983
+ if (node.operator.operator === "=") {
984
+ if (!kysely.ValueNode.is(rightOperand) || rightOperand.value === null || rightOperand.value === void 0) return;
985
+ return [rightOperand.value];
986
+ }
987
+ if (node.operator.operator === "in") {
988
+ if (kysely.PrimitiveValueListNode.is(rightOperand)) {
989
+ const values = rightOperand.values.filter((v) => v !== null && v !== void 0);
990
+ return values.length > 0 ? values : void 0;
991
+ }
992
+ if (kysely.ValueListNode.is(rightOperand)) {
993
+ const values = rightOperand.values.filter((v) => kysely.ValueNode.is(v) && v.value !== null && v.value !== void 0);
994
+ return values.length > 0 ? values.map((v) => v.value) : void 0;
995
+ }
996
+ return;
997
+ }
948
998
  }
949
999
  async postUpdateCheck(model, beforeUpdateInfo, updateResult, proceed) {
950
1000
  let postUpdateRows;
@@ -1123,6 +1173,10 @@ var PolicyHandler = class extends kysely.OperationNodeTransformer {
1123
1173
  const fieldDef = _zenstackhq_orm.QueryUtils.getField(this.client.$schema, model, f);
1124
1174
  const owningTable = fieldDef?.originModel ?? model;
1125
1175
  if (fieldDef?.originModel) baseModelsToJoin.add(fieldDef.originModel);
1176
+ if (fieldDef?.computed) {
1177
+ rejectParameterizedComputedField(fieldDef, model);
1178
+ return kysely.SelectionNode.create(kysely.AliasNode.create(this.dialect.fieldRef(owningTable, f, owningTable).toOperationNode(), kysely.IdentifierNode.create(f)));
1179
+ }
1126
1180
  return kysely.SelectionNode.create(kysely.ReferenceNode.create(kysely.ColumnNode.create(f), kysely.TableNode.create(owningTable)));
1127
1181
  });
1128
1182
  const idFields = _zenstackhq_orm.QueryUtils.requireIdFields(this.client.$schema, model);
@@ -1213,6 +1267,17 @@ var PolicyHandler = class extends kysely.OperationNodeTransformer {
1213
1267
  }
1214
1268
  return combinedPolicy;
1215
1269
  }
1270
+ /**
1271
+ * Builds the update policy filter for one side of an implicit many-to-many relation.
1272
+ *
1273
+ * If the relation field declares field-level `update` policies, they take precedence over
1274
+ * the model-level policy for this side; otherwise the model-level `update` policy applies
1275
+ * (preserving the pre-existing behavior).
1276
+ */
1277
+ buildM2mSidePolicyFilter(model, field) {
1278
+ if (this.getFieldPolicies(model, field, "update").length > 0) return this.buildFieldPolicyFilter(model, field, "update");
1279
+ return this.buildPolicyFilter(model, void 0, "update");
1280
+ }
1216
1281
  onlyReturningId(node) {
1217
1282
  if (!node.returning) return true;
1218
1283
  const { mutationModel } = this.getMutationModel(node);
@@ -1245,9 +1310,9 @@ var PolicyHandler = class extends kysely.OperationNodeTransformer {
1245
1310
  (0, _zenstackhq_common_helpers.invariant)(aValue !== null && aValue !== void 0, "A value cannot be null or undefined");
1246
1311
  (0, _zenstackhq_common_helpers.invariant)(bValue !== null && bValue !== void 0, "B value cannot be null or undefined");
1247
1312
  const eb = (0, kysely.expressionBuilder)();
1248
- const filterA = this.buildPolicyFilter(m2m.firstModel, void 0, "update");
1313
+ const filterA = this.buildM2mSidePolicyFilter(m2m.firstModel, m2m.firstField);
1249
1314
  const queryA = eb.selectFrom(m2m.firstModel).where(eb(eb.ref(`${m2m.firstModel}.${m2m.firstIdField}`), "=", aValue)).select(() => new kysely.ExpressionWrapper(filterA).as("_"));
1250
- const filterB = this.buildPolicyFilter(m2m.secondModel, void 0, "update");
1315
+ const filterB = this.buildM2mSidePolicyFilter(m2m.secondModel, m2m.secondField);
1251
1316
  const queryB = eb.selectFrom(m2m.secondModel).where(eb(eb.ref(`${m2m.secondModel}.${m2m.secondIdField}`), "=", bValue)).select(() => new kysely.ExpressionWrapper(filterB).as("_"));
1252
1317
  const result = await proceed({
1253
1318
  kind: "SelectQueryNode",
@@ -1484,10 +1549,10 @@ var PolicyHandler = class extends kysely.OperationNodeTransformer {
1484
1549
  getModelPolicyFilterForManyToManyJoinTable(tableName, alias, operation) {
1485
1550
  const m2m = this.resolveManyToManyJoinTable(tableName);
1486
1551
  if (!m2m) return;
1487
- const checkForOperation = operation === "read" ? "read" : "update";
1552
+ const isRead = operation === "read";
1488
1553
  const joinTable = alias ?? tableName;
1489
- const aQuery = this.eb.selectFrom(m2m.firstModel).whereRef(`${m2m.firstModel}.${m2m.firstIdField}`, "=", `${joinTable}.A`).select(() => new kysely.ExpressionWrapper(this.buildPolicyFilter(m2m.firstModel, void 0, checkForOperation)).as("$conditionA"));
1490
- const bQuery = this.eb.selectFrom(m2m.secondModel).whereRef(`${m2m.secondModel}.${m2m.secondIdField}`, "=", `${joinTable}.B`).select(() => new kysely.ExpressionWrapper(this.buildPolicyFilter(m2m.secondModel, void 0, checkForOperation)).as("$conditionB"));
1554
+ const aQuery = this.eb.selectFrom(m2m.firstModel).whereRef(`${m2m.firstModel}.${m2m.firstIdField}`, "=", `${joinTable}.A`).select(() => new kysely.ExpressionWrapper(isRead ? this.buildPolicyFilter(m2m.firstModel, void 0, "read") : this.buildM2mSidePolicyFilter(m2m.firstModel, m2m.firstField)).as("$conditionA"));
1555
+ const bQuery = this.eb.selectFrom(m2m.secondModel).whereRef(`${m2m.secondModel}.${m2m.secondIdField}`, "=", `${joinTable}.B`).select(() => new kysely.ExpressionWrapper(isRead ? this.buildPolicyFilter(m2m.secondModel, void 0, "read") : this.buildM2mSidePolicyFilter(m2m.secondModel, m2m.secondField)).as("$conditionB"));
1491
1556
  return this.eb.and([aQuery, bQuery]).toOperationNode();
1492
1557
  }
1493
1558
  tryRejectNonexistentModel(model) {