@web-ts-toolkit/access-router 0.66.0 → 0.67.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs CHANGED
@@ -65,7 +65,7 @@ function assertAuthorizationModeOptions(value, model) {
65
65
  normalizeAuthorizationMode(slot.value);
66
66
  }
67
67
  }
68
- var retiredAuthorizationOptions, authorizationModeKeys, serverAuthorizationControls;
68
+ var retiredAuthorizationOptions, authorizationModeKeys, authorizationModeOperations, serverAuthorizationControls;
69
69
  var init_authorization_modes = __esm({
70
70
  "src/acl/authorization-modes.ts"() {
71
71
  retiredAuthorizationOptions = [
@@ -80,7 +80,18 @@ var init_authorization_modes = __esm({
80
80
  "unsafeUseListAuthorizationFastPath",
81
81
  "unsafeUseReadAuthorizationFastPath"
82
82
  ];
83
- authorizationModeKeys = ["readAuthorizationMode", "listAuthorizationMode"];
83
+ authorizationModeKeys = [
84
+ "readAuthorizationMode",
85
+ "listAuthorizationMode",
86
+ "createAuthorizationMode",
87
+ "updateAuthorizationMode"
88
+ ];
89
+ authorizationModeOperations = {
90
+ readAuthorizationMode: "read",
91
+ listAuthorizationMode: "list",
92
+ createAuthorizationMode: "create",
93
+ updateAuthorizationMode: "update"
94
+ };
84
95
  serverAuthorizationControls = [...retiredAuthorizationOptions, ...authorizationModeKeys];
85
96
  }
86
97
  });
@@ -3055,6 +3066,158 @@ var init_data_manager = __esm({
3055
3066
  }
3056
3067
  });
3057
3068
 
3069
+ // src/operation-access.ts
3070
+ function isOperationAccessMemberPath(access) {
3071
+ const keys2 = access.split(".");
3072
+ if (operations.has(keys2[0]) && members.has(keys2[1])) return true;
3073
+ return keys2[0] === "subs" && keys2[1] !== "" && subOperations.has(keys2[2]) && members.has(keys2[3]);
3074
+ }
3075
+ function readOwnOption(root, key) {
3076
+ let value = root;
3077
+ for (const part of key.split(".")) {
3078
+ if (value === null || typeof value !== "object") return void 0;
3079
+ const slot = Object.getOwnPropertyDescriptor(value, part);
3080
+ if (!slot || !("value" in slot)) return void 0;
3081
+ value = slot.value;
3082
+ }
3083
+ return value;
3084
+ }
3085
+ function createOperationAccessReaders(options, defaults2) {
3086
+ return {
3087
+ readOption: (key) => readOwnOption(options, key),
3088
+ readDefaultOption: defaults2 === void 0 ? void 0 : (key) => readOwnOption(defaults2, key)
3089
+ };
3090
+ }
3091
+ function operationDefault(value) {
3092
+ if (!isRecord(value)) return scalarGuard(value);
3093
+ if (Reflect.ownKeys(value).some((key) => typeof key !== "string" || !members.has(key))) return false;
3094
+ return scalarGuard(readOwnOption(value, "default"));
3095
+ }
3096
+ function selectOperationAccessGuard({
3097
+ baseAccess,
3098
+ context,
3099
+ readOption,
3100
+ readDefaultOption,
3101
+ subdocuments = false
3102
+ }) {
3103
+ const keys2 = baseAccess.split(".");
3104
+ if (isRemovedOperationAccess(baseAccess) || isOperationAccessMemberPath(baseAccess) || keys2[0] === "subs" && isRemovedOperationAccess(keys2[2]))
3105
+ return false;
3106
+ if (context !== void 0 && !["basic", "advanced", "root"].includes(context)) return false;
3107
+ const exact = (key) => {
3108
+ const value = readOption(key);
3109
+ return value === void 0 ? readDefaultOption?.(key) : value;
3110
+ };
3111
+ const contextGuard = (key, supported) => context === void 0 || !supported ? void 0 : scalarGuard(exact(`${key}.${context}`));
3112
+ let access = baseAccess;
3113
+ if (subdocuments && keys2[0] === "subs") {
3114
+ if (keys2.length < 3 || keys2[1] === "") return false;
3115
+ const fieldKey = `operationAccess.subs.${keys2[1]}`;
3116
+ const operationKey2 = `operationAccess.${baseAccess}`;
3117
+ const selected2 = contextGuard(operationKey2, keys2.length === 3 && subOperations.has(keys2[2]));
3118
+ if (selected2 !== void 0) return selected2;
3119
+ const operation2 = exact(operationKey2);
3120
+ if (operation2 !== void 0) {
3121
+ const guard2 = keys2.length === 3 && subOperations.has(keys2[2]) ? operationDefault(operation2) : scalarGuard(operation2);
3122
+ if (guard2 !== void 0) return guard2;
3123
+ }
3124
+ const field = exact(fieldKey);
3125
+ if (field !== void 0) return scalarGuard(field);
3126
+ access = keys2[2];
3127
+ }
3128
+ const operationKey = `operationAccess.${access}`;
3129
+ const selected = contextGuard(operationKey, operations.has(access));
3130
+ if (selected !== void 0) return selected;
3131
+ const operation = readOption(operationKey);
3132
+ if (operation !== void 0) {
3133
+ const guard2 = operations.has(access) ? operationDefault(operation) : scalarGuard(operation);
3134
+ if (guard2 !== void 0) return guard2;
3135
+ }
3136
+ const outerDefault = readOption("operationAccess.default");
3137
+ if (outerDefault !== void 0) return scalarGuard(outerDefault);
3138
+ const outer = readOption("operationAccess");
3139
+ if (outer !== void 0) return scalarGuard(outer);
3140
+ const inherited = readDefaultOption?.(operationKey);
3141
+ return operations.has(access) ? operationDefault(inherited) : scalarGuard(inherited);
3142
+ }
3143
+ async function resolveRouteOperationAccess({
3144
+ canActivate,
3145
+ ...selection
3146
+ }) {
3147
+ const guard2 = selectOperationAccessGuard(selection);
3148
+ return guard2 === void 0 ? false : canActivate(guard2);
3149
+ }
3150
+ function rejectRemovedKey(key, prefix) {
3151
+ const context = key.startsWith("basic") ? "basic" : "advanced";
3152
+ const operation = key.slice(context.length);
3153
+ const replacement = `${operation[0].toLowerCase()}${operation.slice(1)}.${context}`;
3154
+ throw new TypeError(
3155
+ `Removed operation-access key "${prefix}${key}"; use "${prefix}${replacement}" instead. Move the operation's former scalar guard to its "default" member when using an object.`
3156
+ );
3157
+ }
3158
+ function assertOperationNode(node, prefix) {
3159
+ if (!node || typeof node !== "object" || Array.isArray(node)) return;
3160
+ for (const key of removedAccesses) if (key in node) rejectRemovedKey(key, prefix);
3161
+ for (const key of Object.getOwnPropertyNames(node)) {
3162
+ const [operation] = key.split(".");
3163
+ if (isRemovedOperationAccess(operation)) rejectRemovedKey(operation, prefix);
3164
+ }
3165
+ }
3166
+ function assertOperationAccessOptions(options) {
3167
+ if (!options || typeof options !== "object") return;
3168
+ for (const key of Object.getOwnPropertyNames(options)) {
3169
+ if (key === "operationAccess" || key.startsWith("operationAccess.")) {
3170
+ assertOperationAccessUpdate(key, options[key]);
3171
+ }
3172
+ }
3173
+ }
3174
+ function assertOperationAccessUpdate(key, value) {
3175
+ const path = key.split(".");
3176
+ if (path[0] !== "operationAccess") return;
3177
+ if (isRemovedOperationAccess(path[1])) rejectRemovedKey(path[1], "operationAccess.");
3178
+ if (path[1] === "subs" && path.length >= 4 && isRemovedOperationAccess(path[3]))
3179
+ rejectRemovedKey(path[3], `operationAccess.subs.${path[2]}.`);
3180
+ if (path.length === 1) {
3181
+ assertOperationNode(value, "operationAccess.");
3182
+ if (value && typeof value === "object" && !Array.isArray(value)) {
3183
+ for (const property of Object.getOwnPropertyNames(value)) {
3184
+ if (property === "subs" || property.startsWith("subs."))
3185
+ assertOperationAccessUpdate(`operationAccess.${property}`, value[property]);
3186
+ }
3187
+ }
3188
+ } else if (path.length === 2 && path[1] === "subs") {
3189
+ if (value && typeof value === "object" && !Array.isArray(value)) {
3190
+ for (const field of Object.getOwnPropertyNames(value))
3191
+ assertOperationAccessUpdate(`operationAccess.subs.${field}`, value[field]);
3192
+ }
3193
+ } else if (path.length === 3 && path[1] === "subs") {
3194
+ assertOperationNode(value, `${key}.`);
3195
+ }
3196
+ }
3197
+ var operations, subOperations, members, removedAccesses, isRemovedOperationAccess, isRecord, scalarGuard;
3198
+ var init_operation_access = __esm({
3199
+ "src/operation-access.ts"() {
3200
+ operations = /* @__PURE__ */ new Set(["new", "list", "read", "create", "update", "upsert", "delete", "count", "distinct"]);
3201
+ subOperations = /* @__PURE__ */ new Set(["list", "read", "create", "update", "delete"]);
3202
+ members = /* @__PURE__ */ new Set(["default", "basic", "advanced", "root"]);
3203
+ removedAccesses = new Set(
3204
+ ["List", "Read", "Create", "Update", "Upsert", "Count", "Distinct"].flatMap((operation) => [
3205
+ `basic${operation}`,
3206
+ `advanced${operation}`
3207
+ ])
3208
+ );
3209
+ isRemovedOperationAccess = (access) => typeof access === "string" && removedAccesses.has(access);
3210
+ isRecord = (value) => value !== null && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
3211
+ scalarGuard = (value) => {
3212
+ if (value === void 0) return void 0;
3213
+ if (typeof value === "boolean" || typeof value === "string" || typeof value === "function")
3214
+ return value;
3215
+ if (Array.isArray(value) && value.every((entry) => typeof entry === "string")) return value;
3216
+ return false;
3217
+ };
3218
+ }
3219
+ });
3220
+
3058
3221
  // src/request-complexity.ts
3059
3222
  import { isArray as isArray4, isPlainObject as isPlainObject10 } from "@web-ts-toolkit/utils";
3060
3223
  function validateRequestComplexity(value, options, scope2 = "request") {
@@ -3458,8 +3621,8 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, populat
3458
3621
  if (!model || !schema || unsupportedScope)
3459
3622
  return fail(label, "requires a static embedded, non-discriminator source scope");
3460
3623
  const type = schema.path(join(schemaPrefix, path));
3461
- const isArray14 = type?.instance === "Array";
3462
- const scalar = type && (isArray14 ? elementType(type) : type);
3624
+ const isArray13 = type?.instance === "Array";
3625
+ const scalar = type && (isArray13 ? elementType(type) : type);
3463
3626
  const ref = type?.options?.ref ?? scalar?.options?.ref;
3464
3627
  if (!scalar || scalar.instance !== "ObjectId" || typeof ref !== "string" || !ref || type?.options?.refPath !== void 0 || scalar.options?.refPath !== void 0)
3465
3628
  return fail(label, `path "${path}" requires a static string ref on an ObjectId scalar or 1D array`);
@@ -3491,7 +3654,12 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, populat
3491
3654
  populatePolicyDefaults,
3492
3655
  ...resolvePopulatePolicy(targetOptions, populatePolicyDefaults),
3493
3656
  permissionSchema: targetOptions.permissionSchema,
3494
- operationAccess: { read: readOption("operationAccess.read") },
3657
+ operationAccess: {
3658
+ read: selectOperationAccessGuard({
3659
+ ...createOperationAccessReaders(targetOptions, defaults2),
3660
+ baseAccess: "read"
3661
+ })
3662
+ },
3495
3663
  baseFilter: { read: readOption("baseFilter.read") },
3496
3664
  overrideFilter: { read: readOption("overrideFilter.read") },
3497
3665
  hydration: targetOptions.hydration
@@ -3514,7 +3682,7 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, populat
3514
3682
  return Object.freeze({
3515
3683
  path,
3516
3684
  sourcePath: join(sourcePrefix, path),
3517
- cardinality: isArray14 ? "array" : "scalar",
3685
+ cardinality: isArray13 ? "array" : "scalar",
3518
3686
  target: captured.target,
3519
3687
  ...normalizeSelection(dependency.select, captured.catalog, label)
3520
3688
  });
@@ -3600,6 +3768,7 @@ var init_virtual_populate_dependencies = __esm({
3600
3768
  "src/acl/virtual-populate-dependencies.ts"() {
3601
3769
  init_query();
3602
3770
  init_manager();
3771
+ init_operation_access();
3603
3772
  init_authorization_snapshot();
3604
3773
  init_field_catalog();
3605
3774
  init_virtual_descriptor();
@@ -3618,6 +3787,100 @@ var init_virtual_populate_dependencies = __esm({
3618
3787
  }
3619
3788
  });
3620
3789
 
3790
+ // src/acl/persisted-dependencies.ts
3791
+ import { types as types8 } from "util";
3792
+ function collectPersistedTopLevel(schema) {
3793
+ return /* @__PURE__ */ new Set([
3794
+ ...Object.keys(schema?.paths ?? {}).map((path) => path.split(".")[0]),
3795
+ ...Object.keys(schema?.obj ?? {})
3796
+ ]);
3797
+ }
3798
+ function capturePersistedDependencies(value, label, storedFields, virtualNames = /* @__PURE__ */ new Set()) {
3799
+ if (value === void 0) return Object.freeze([]);
3800
+ if (!Array.isArray(value) || types8.isProxy(value) || Object.getPrototypeOf(value) !== Array.prototype)
3801
+ throw new TypeError(`${label}: dependsOn must be an array of top-level persisted field names`);
3802
+ const length = Object.getOwnPropertyDescriptor(value, "length").value;
3803
+ if (length > 2e4 || Reflect.ownKeys(value).length !== length + 1)
3804
+ throw new TypeError(`${label}: dependsOn must be a dense array of persisted field names`);
3805
+ const result2 = [];
3806
+ for (let index = 0; index < length; index++) {
3807
+ const slot = Object.getOwnPropertyDescriptor(value, String(index));
3808
+ if (!slot || !("value" in slot) || typeof slot.value !== "string" || !slot.value)
3809
+ throw new TypeError(`${label}: dependsOn entries must be non-empty strings`);
3810
+ const dep = slot.value;
3811
+ if (dep.includes("."))
3812
+ throw new TypeError(`${label}: dependsOn "${dep}" must be a top-level persisted name (dotted paths rejected)`);
3813
+ if (!isSafeOutputPath(dep)) throw new TypeError(`${label}: unsafe dependsOn field "${dep}"`);
3814
+ if (virtualNames.has(dep)) throw new TypeError(`${label}: dependsOn "${dep}" must not reference another virtual`);
3815
+ if (storedFields && !storedFields.has(dep))
3816
+ throw new TypeError(`${label}: dependsOn "${dep}" is not a persisted field in its scope`);
3817
+ result2.push(dep);
3818
+ }
3819
+ return Object.freeze([...new Set(result2)]);
3820
+ }
3821
+ var init_persisted_dependencies = __esm({
3822
+ "src/acl/persisted-dependencies.ts"() {
3823
+ init_field_catalog();
3824
+ }
3825
+ });
3826
+
3827
+ // src/acl/document-permissions-definition.ts
3828
+ import { types as types9 } from "util";
3829
+ function dataRecord(value, label) {
3830
+ if (!value || typeof value !== "object" || types9.isProxy(value))
3831
+ throw new TypeError(`${label}: expected a function, { get, dependsOn? }, or per-access record`);
3832
+ const prototype = Object.getPrototypeOf(value);
3833
+ if (prototype !== Object.prototype && prototype !== null)
3834
+ throw new TypeError(`${label}: definition must be a plain object`);
3835
+ const result2 = /* @__PURE__ */ Object.create(null);
3836
+ const keys2 = Reflect.ownKeys(value);
3837
+ if (keys2.length > 2e4) throw new TypeError(`${label}: too many definition entries`);
3838
+ for (const key of keys2) {
3839
+ if (typeof key !== "string" || ["__proto__", "constructor", "prototype"].includes(key))
3840
+ throw new TypeError(`${label}: unsafe definition key`);
3841
+ const slot = Object.getOwnPropertyDescriptor(value, key);
3842
+ if (!slot.enumerable || !("value" in slot))
3843
+ throw new TypeError(`${label}: definition entries must be enumerable data properties`);
3844
+ Object.defineProperty(result2, key, { value: slot.value, enumerable: true });
3845
+ }
3846
+ return result2;
3847
+ }
3848
+ function captureLeaf(value, label, scope2) {
3849
+ if (typeof value === "function") return value;
3850
+ const record3 = dataRecord(value, label);
3851
+ if (typeof record3.get !== "function") throw new TypeError(`${label}: descriptor.get must be callable`);
3852
+ if (Object.keys(record3).some((key) => key !== "get" && key !== "dependsOn"))
3853
+ throw new TypeError(`${label}: descriptor accepts only get/dependsOn; cannot mix per-access keys`);
3854
+ return Object.freeze({
3855
+ get: record3.get,
3856
+ dependsOn: capturePersistedDependencies(record3.dependsOn, label, scope2.storedFields, scope2.virtualNames)
3857
+ });
3858
+ }
3859
+ function captureDocumentPermissionsDefinition(value, scope2 = {}) {
3860
+ if (value === void 0) return void 0;
3861
+ if (typeof value === "function") return value;
3862
+ const record3 = dataRecord(value, "docPermissions");
3863
+ if (Object.hasOwn(record3, "get") || Object.hasOwn(record3, "dependsOn"))
3864
+ return captureLeaf(record3, "docPermissions", scope2);
3865
+ const entries = Object.entries(record3).map(([access, leaf]) => {
3866
+ if (!/^[A-Za-z_][A-Za-z0-9_$]*$/.test(access))
3867
+ throw new TypeError(`docPermissions: unsafe or dotted access "${access}"`);
3868
+ return [access, leaf === void 0 ? void 0 : captureLeaf(leaf, `docPermissions.${access}`, scope2)];
3869
+ });
3870
+ return Object.freeze(Object.fromEntries(entries));
3871
+ }
3872
+ function resolveDocumentPermissionsDefinition(value, access) {
3873
+ const captured = captureDocumentPermissionsDefinition(value);
3874
+ const leaf = typeof captured === "function" || captured && Object.hasOwn(captured, "get") ? captured : Object.getOwnPropertyDescriptor(captured ?? {}, access)?.value ?? Object.getOwnPropertyDescriptor(captured ?? {}, "default")?.value;
3875
+ if (leaf === void 0) return void 0;
3876
+ return typeof leaf === "function" ? Object.freeze({ get: leaf, dependsOn: Object.freeze([]) }) : Object.freeze({ get: leaf.get, dependsOn: leaf.dependsOn ?? Object.freeze([]) });
3877
+ }
3878
+ var init_document_permissions_definition = __esm({
3879
+ "src/acl/document-permissions-definition.ts"() {
3880
+ init_persisted_dependencies();
3881
+ }
3882
+ });
3883
+
3621
3884
  // src/runtime.ts
3622
3885
  import mongoose from "mongoose";
3623
3886
  import mschema2Jsonschema from "mongoose-schema-jsonschema";
@@ -3646,10 +3909,13 @@ var init_runtime = __esm({
3646
3909
  init_logger_default();
3647
3910
  init_manager();
3648
3911
  init_data_manager();
3912
+ init_operation_access();
3649
3913
  init_data_values();
3650
3914
  init_request_complexity();
3651
3915
  init_virtual_descriptor();
3652
3916
  init_virtual_populate_dependencies();
3917
+ init_document_permissions_definition();
3918
+ init_persisted_dependencies();
3653
3919
  init_authorization_modes();
3654
3920
  mongooseJsonSchemaInitialized = false;
3655
3921
  ensureMongooseJsonSchemaInitialized = () => {
@@ -3660,8 +3926,7 @@ var init_runtime = __esm({
3660
3926
  pluralize = mongoose.pluralize();
3661
3927
  FIELD_ACCESS_KEYS = ["list", "create", "read", "update"];
3662
3928
  defaultModelOptions = {
3663
- basePath: null,
3664
- alwaysSelectFields: []
3929
+ basePath: null
3665
3930
  };
3666
3931
  modelOverrides = (options) => {
3667
3932
  const result2 = Object.fromEntries(
@@ -3759,22 +4024,7 @@ var init_runtime = __esm({
3759
4024
  }
3760
4025
  return false;
3761
4026
  };
3762
- collectStoredTopLevel = (schema) => {
3763
- const fields = /* @__PURE__ */ new Set();
3764
- if (!schema) return fields;
3765
- const paths = schema.paths;
3766
- if (paths) {
3767
- for (const p of Object.keys(paths)) {
3768
- const top = p.split(".")[0];
3769
- if (top) fields.add(top);
3770
- }
3771
- }
3772
- const obj = schema.obj;
3773
- if (obj) {
3774
- for (const k of Object.keys(obj)) fields.add(k);
3775
- }
3776
- return fields;
3777
- };
4027
+ collectStoredTopLevel = collectPersistedTopLevel;
3778
4028
  getChildSchemaForField = (parentSchema, fieldName) => {
3779
4029
  if (!parentSchema) return null;
3780
4030
  try {
@@ -3813,32 +4063,7 @@ var init_runtime = __esm({
3813
4063
  );
3814
4064
  };
3815
4065
  validateVirtualDependsOn = (dependsOn, entryLabel, storedFields, siblingVirtualNames) => {
3816
- if (dependsOn === void 0) return [];
3817
- if (!isArray5(dependsOn)) {
3818
- throw new Error(`Virtual ${entryLabel}: dependsOn must be an array of top-level persisted field names`);
3819
- }
3820
- const list = dependsOn;
3821
- for (const dep of list) {
3822
- if (!isString4(dep) || dep.length === 0) {
3823
- throw new Error(`Virtual ${entryLabel}: dependsOn entries must be non-empty strings`);
3824
- }
3825
- if (dep.includes(".")) {
3826
- throw new Error(
3827
- `Virtual ${entryLabel}: dependsOn "${dep}" must be a top-level persisted name relative to its scope (dotted paths rejected)`
3828
- );
3829
- }
3830
- if (siblingVirtualNames.has(dep)) {
3831
- throw new Error(
3832
- `Virtual ${entryLabel}: dependsOn "${dep}" must not reference another virtual (virtual-to-virtual rejected)`
3833
- );
3834
- }
3835
- if (!storedFields.has(dep)) {
3836
- throw new Error(
3837
- `Virtual ${entryLabel}: dependsOn "${dep}" is not a persisted field in its scope (validated against the receiving Mongoose schema/child scope)`
3838
- );
3839
- }
3840
- }
3841
- return list;
4066
+ return [...capturePersistedDependencies(dependsOn, `Virtual ${entryLabel}`, storedFields, siblingVirtualNames)];
3842
4067
  };
3843
4068
  validateVirtualLeafValue = (value, entryLabel, storedFields, siblingVirtualNames, sharedDependsOn) => {
3844
4069
  if (isFunction2(value)) return;
@@ -4013,6 +4238,7 @@ var init_runtime = __esm({
4013
4238
  this.defaultModelOptions = new OptionsManager({
4014
4239
  listHardLimit: DEFAULT_LIST_HARD_LIMIT,
4015
4240
  documentPermissionField: "_permissions",
4241
+ disableFieldPermissions: true,
4016
4242
  idParam: "id",
4017
4243
  idField: "_id",
4018
4244
  parentPath: "/",
@@ -4023,7 +4249,9 @@ var init_runtime = __esm({
4023
4249
  requireOperationAccessForPopulateDependencies: true,
4024
4250
  modelPermissionPrefix: "",
4025
4251
  readAuthorizationMode: "isolated",
4026
- listAuthorizationMode: "isolated"
4252
+ listAuthorizationMode: "isolated",
4253
+ createAuthorizationMode: "isolated",
4254
+ updateAuthorizationMode: "isolated"
4027
4255
  }).build();
4028
4256
  this.modelOptions = {};
4029
4257
  this.modelOptionOverrides = {};
@@ -4164,15 +4392,18 @@ var init_runtime = __esm({
4164
4392
  assertAuthorizationModeOptions(snapshot.globalOptions, false);
4165
4393
  assertNoServerModelControls(snapshot.globalOptions, reject);
4166
4394
  assertAuthorizationModeOptions(snapshot.defaultModelOptions, true);
4395
+ assertOperationAccessOptions(snapshot.defaultModelOptions);
4167
4396
  assertNoServerModelControls(snapshot.defaultModelOptions, reject, "model-options");
4168
4397
  assertPublicDefaults(snapshot.defaultModelOptions.defaults);
4169
4398
  for (const options of [...Object.values(snapshot.modelOptions), ...Object.values(snapshot.modelOptionOverrides)]) {
4170
4399
  assertAuthorizationModeOptions(options, true);
4400
+ assertOperationAccessOptions(options);
4171
4401
  assertNoServerModelControls(options, reject, "model-options");
4172
4402
  assertPublicDefaults(options.defaults);
4173
4403
  }
4174
4404
  for (const options of Object.values(snapshot.dataOptions)) {
4175
4405
  assertAuthorizationModeOptions(options, false);
4406
+ assertOperationAccessOptions(options);
4176
4407
  assertNoServerModelControls(options, reject, "data-options");
4177
4408
  }
4178
4409
  this.globalOptions.restore(snapshot.globalOptions);
@@ -4260,6 +4491,7 @@ var init_runtime = __esm({
4260
4491
  /** Update inherited model defaults shallowly. Explicit model values and captured calls are unchanged. */
4261
4492
  setDefaultModelOptions(options) {
4262
4493
  assertAuthorizationModeOptions(options, true);
4494
+ assertOperationAccessOptions(options);
4263
4495
  assertNoServerModelControls(
4264
4496
  options,
4265
4497
  (detail) => {
@@ -4281,6 +4513,7 @@ var init_runtime = __esm({
4281
4513
  setDefaultModelOption(key, value) {
4282
4514
  assertAuthorizationModeKey(key, true);
4283
4515
  const keyStr = key;
4516
+ assertOperationAccessUpdate(keyStr, value);
4284
4517
  if (authorizationModeKeys.includes(keyStr)) {
4285
4518
  this.setDefaultModelOptions({ [keyStr]: value });
4286
4519
  return;
@@ -4334,15 +4567,20 @@ var init_runtime = __esm({
4334
4567
  return cloneOptionsSnapshot(effective);
4335
4568
  }
4336
4569
  validateModelOptions(modelName, options, proposed) {
4337
- validateVirtualsTree(
4338
- this.getModelInstance(modelName),
4339
- options.virtuals,
4340
- options.documentPermissionField ?? "_permissions",
4341
- modelName
4342
- );
4570
+ assertOperationAccessOptions(options);
4571
+ const model = this.getModelInstance(modelName);
4572
+ validateVirtualsTree(model, options.virtuals, options.documentPermissionField ?? "_permissions", modelName);
4573
+ captureDocumentPermissionsDefinition(options.docPermissions, {
4574
+ storedFields: collectPersistedTopLevel(model?.schema),
4575
+ virtualNames: /* @__PURE__ */ new Set([
4576
+ ...Object.keys(model?.schema.virtuals ?? {}),
4577
+ ...Object.entries(options.virtuals ?? {}).filter(([, value]) => value !== void 0 && !isVirtualContainerValue2(value)).map(([name]) => name)
4578
+ ])
4579
+ });
4343
4580
  captureVirtualPopulateDependencies(this, modelName, options, void 0, proposed);
4344
4581
  }
4345
4582
  publishDefaultModelOptions(options) {
4583
+ assertOperationAccessOptions(options);
4346
4584
  const next = { ...options };
4347
4585
  const defaults2 = cloneOptionsSnapshot(next);
4348
4586
  const models = new Map(
@@ -4375,10 +4613,10 @@ var init_runtime = __esm({
4375
4613
  if (options[key] !== "trusted" || before.get(modelName)?.[key] === "trusted") continue;
4376
4614
  try {
4377
4615
  this.getGlobalOption("logger")?.warn?.(
4378
- "Trusted authorization source mode enabled; projected source/document-hook input may be borrowed. Actor, policy, facts, getter views and selected output bounds remain owned.",
4616
+ "Trusted authorization output source mode enabled; admitted source/document-hook input may be borrowed. Write input is unchanged. Actor, policy, facts, getter views and selected output bounds remain owned.",
4379
4617
  {
4380
4618
  modelName,
4381
- access: key === "readAuthorizationMode" ? "read" : "list",
4619
+ access: authorizationModeOperations[key],
4382
4620
  category: "trustedAuthorizationSource"
4383
4621
  }
4384
4622
  );
@@ -4430,6 +4668,7 @@ var init_runtime = __esm({
4430
4668
  */
4431
4669
  setModelOptions(modelName, options) {
4432
4670
  assertAuthorizationModeOptions(options, true);
4671
+ assertOperationAccessOptions(options);
4433
4672
  assertNoServerModelControls(
4434
4673
  options,
4435
4674
  (detail) => {
@@ -4438,6 +4677,12 @@ var init_runtime = __esm({
4438
4677
  "model-options"
4439
4678
  );
4440
4679
  assertPublicDefaults(options.defaults);
4680
+ if ("docPermissions" in options) {
4681
+ const slot = Object.getOwnPropertyDescriptor(options, "docPermissions");
4682
+ if (!slot || !("value" in slot) || !slot.enumerable)
4683
+ throw new TypeError("docPermissions must be an enumerable data property");
4684
+ options = { ...options, docPermissions: captureDocumentPermissionsDefinition(slot.value) };
4685
+ }
4441
4686
  options = normalizePopulatePolicyOptions(options);
4442
4687
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
4443
4688
  const overrides = modelOverrides({ ...this.modelOptionOverrides[modelName], ...options });
@@ -4453,6 +4698,17 @@ var init_runtime = __esm({
4453
4698
  setModelOption(modelName, key, value) {
4454
4699
  assertAuthorizationModeKey(key, true);
4455
4700
  const keyStr = key;
4701
+ assertOperationAccessUpdate(keyStr, value);
4702
+ if (keyStr === "docPermissions") {
4703
+ value = captureDocumentPermissionsDefinition(value);
4704
+ } else if (keyStr.startsWith("docPermissions.")) {
4705
+ const path2 = keyStr.slice("docPermissions.".length);
4706
+ if (path2.includes(".") || path2 === "get" || path2 === "dependsOn")
4707
+ throw new TypeError(
4708
+ "docPermissions dotted setters replace an access definition; set { get, dependsOn? } together"
4709
+ );
4710
+ captureDocumentPermissionsDefinition({ [path2]: value });
4711
+ }
4456
4712
  if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
4457
4713
  const hydration = normalizeHydrationUpdate(this.resolveModelOptions(modelName).hydration, keyStr, value);
4458
4714
  this.setModelOptions(modelName, { hydration });
@@ -4485,7 +4741,10 @@ var init_runtime = __esm({
4485
4741
  return;
4486
4742
  }
4487
4743
  const current = this.resolveModelOptions(modelName);
4488
- const nested = cloneModelOptionForUpdate(isPlainObject14(current[root]) ? current[root] : {});
4744
+ const directDocumentPermissions = root === "docPermissions" && current[root] && typeof current[root] === "object" && Object.hasOwn(current[root], "get");
4745
+ const nested = cloneModelOptionForUpdate(
4746
+ isPlainObject14(current[root]) && !directDocumentPermissions ? current[root] : {}
4747
+ );
4489
4748
  if (root === "virtuals" && value === void 0) {
4490
4749
  const parent = path.length === 1 ? nested : get5(nested, path.slice(0, -1));
4491
4750
  if (isPlainObject14(parent)) delete parent[path[path.length - 1]];
@@ -4500,8 +4759,9 @@ var init_runtime = __esm({
4500
4759
  /**
4501
4760
  * Generic stored exact → parent.default → parent lookup; only undefined falls through.
4502
4761
  * The exact runtime-model-default path is the final fallback if the stored parent is
4503
- * absent. This is not the route-specific variant-to-base resolver; use
4504
- * getExactModelOption to inspect a variant including its exact model-default fallback.
4762
+ * absent. This raw generic lookup is not the final nested operation-entry resolver;
4763
+ * it may return an operation object. getExactModelOption inspects a member including
4764
+ * its same-owner exact model-default fallback, without resolving entry policy.
4505
4765
  */
4506
4766
  getModelOption(modelName, key, defaultValue) {
4507
4767
  const manager = this.getOrCreateModelOptions(modelName);
@@ -4511,7 +4771,7 @@ var init_runtime = __esm({
4511
4771
  );
4512
4772
  return getNestedOption(manager, key, defaultModelValue);
4513
4773
  }
4514
- /** Exact stored path, then the same runtime-model-default path; no parent/default or variant-to-base lookup. */
4774
+ /** Exact stored path, then the same runtime-model-default path; no parent/default or final entry resolution. */
4515
4775
  getExactModelOption(modelName, key) {
4516
4776
  const manager = this.getOrCreateModelOptions(modelName);
4517
4777
  const defaultModelValue = this.getDefaultModelOption(key);
@@ -4594,6 +4854,7 @@ var init_runtime = __esm({
4594
4854
  }
4595
4855
  setDataOptions(dataName, options) {
4596
4856
  assertAuthorizationModeOptions(options, false);
4857
+ assertOperationAccessOptions(options);
4597
4858
  assertNoServerModelControls(
4598
4859
  options,
4599
4860
  (detail) => {
@@ -4606,6 +4867,7 @@ var init_runtime = __esm({
4606
4867
  }
4607
4868
  setDataOption(dataName, key, value) {
4608
4869
  assertAuthorizationModeKey(key, false);
4870
+ assertOperationAccessUpdate(key, value);
4609
4871
  const proposed = {};
4610
4872
  set4(proposed, key, value);
4611
4873
  assertNoServerModelControls(
@@ -4700,7 +4962,7 @@ var init_global_options = __esm({
4700
4962
  });
4701
4963
 
4702
4964
  // src/options/model-options.ts
4703
- var getRuntime3, setModelOptions, setModelOption, getModelOptions, getModelOption, getExactModelOption, getModelNames, getModelJsonSchema, registerModelInstance, hasModelInstance, getModelInstance;
4965
+ var getRuntime3, setModelOptions, setModelOption, getModelOptions, getModelOption, getModelNames, getModelJsonSchema, registerModelInstance, hasModelInstance, getModelInstance;
4704
4966
  var init_model_options = __esm({
4705
4967
  "src/options/model-options.ts"() {
4706
4968
  init_runtime();
@@ -4718,9 +4980,6 @@ var init_model_options = __esm({
4718
4980
  getModelOption = (modelName, key, defaultValue) => {
4719
4981
  return getRuntime3().getModelOption(modelName, key, defaultValue);
4720
4982
  };
4721
- getExactModelOption = (modelName, key) => {
4722
- return getRuntime3().getExactModelOption(modelName, key);
4723
- };
4724
4983
  getModelNames = () => {
4725
4984
  return (getActiveRuntime() ?? defaultRuntime).getModelNames();
4726
4985
  };
@@ -4762,7 +5021,7 @@ var init_default_model_options = __esm({
4762
5021
  });
4763
5022
 
4764
5023
  // src/options/data-options.ts
4765
- var getRuntime5, getDataOptions, getDataOption, getExactDataOption;
5024
+ var getRuntime5, getDataOptions, getDataOption;
4766
5025
  var init_data_options = __esm({
4767
5026
  "src/options/data-options.ts"() {
4768
5027
  init_runtime();
@@ -4774,9 +5033,6 @@ var init_data_options = __esm({
4774
5033
  getDataOption = (dataName, key, defaultValue) => {
4775
5034
  return getRuntime5().getDataOption(dataName, key, defaultValue);
4776
5035
  };
4777
- getExactDataOption = (dataName, key) => {
4778
- return getRuntime5().getExactDataOption(dataName, key);
4779
- };
4780
5036
  }
4781
5037
  });
4782
5038
 
@@ -4995,11 +5251,11 @@ var init_logger_helpers = __esm({
4995
5251
 
4996
5252
  // src/index.ts
4997
5253
  init_authorization_modes();
4998
- import { isUndefined as isUndefined4 } from "@web-ts-toolkit/utils";
5254
+ import { isUndefined as isUndefined3 } from "@web-ts-toolkit/utils";
4999
5255
 
5000
5256
  // src/middleware.ts
5001
5257
  import JsonRouter5 from "@web-ts-toolkit/express-json-router";
5002
- import { isArray as isArray13, isFunction as isFunction7, isPlainObject as isPlainObject29, isString as isString7 } from "@web-ts-toolkit/utils";
5258
+ import { isArray as isArray12, isFunction as isFunction7, isPlainObject as isPlainObject29, isString as isString7 } from "@web-ts-toolkit/utils";
5003
5259
 
5004
5260
  // src/core.ts
5005
5261
  init_public_admission();
@@ -5008,11 +5264,10 @@ import {
5008
5264
  castArray as castArray4,
5009
5265
  compact as compact3,
5010
5266
  forEach as forEach6,
5011
- isArray as isArray12,
5267
+ isArray as isArray11,
5012
5268
  isBoolean as isBoolean5,
5013
5269
  isFunction as isFunction6,
5014
5270
  isString as isString6,
5015
- isUndefined,
5016
5271
  reduce as reduce2,
5017
5272
  uniq as uniq3
5018
5273
  } from "@web-ts-toolkit/utils";
@@ -5082,7 +5337,7 @@ import {
5082
5337
  flatten,
5083
5338
  forEach as forEach3,
5084
5339
  get as get7,
5085
- isArray as isArray9,
5340
+ isArray as isArray8,
5086
5341
  isPlainObject as isPlainObject19,
5087
5342
  set as set5,
5088
5343
  uniq
@@ -5092,7 +5347,7 @@ import {
5092
5347
  import { isPlainObject as isPlainObject15 } from "@web-ts-toolkit/utils";
5093
5348
 
5094
5349
  // src/acl/document-stage.ts
5095
- import { types as types9 } from "util";
5350
+ import { types as types11 } from "util";
5096
5351
  import { Document as Document3 } from "mongoose";
5097
5352
 
5098
5353
  // src/acl/service-authorization.ts
@@ -5131,6 +5386,22 @@ function serviceAuthorizationInput(policy, targets) {
5131
5386
  }
5132
5387
  var calls = /* @__PURE__ */ new WeakMap();
5133
5388
  var capturedActors = /* @__PURE__ */ new WeakSet();
5389
+ function storeCallRecord(call, record3) {
5390
+ calls.set(
5391
+ call,
5392
+ Object.assign(
5393
+ /* @__PURE__ */ Object.create(null),
5394
+ {
5395
+ queryOrigin: void 0,
5396
+ writeOrigin: void 0,
5397
+ writeOutputBranch: void 0,
5398
+ fieldPolicyOwner: void 0,
5399
+ view: void 0
5400
+ },
5401
+ record3
5402
+ )
5403
+ );
5404
+ }
5134
5405
  function clearOutputHelperAuthorization(call) {
5135
5406
  if (callRecord(call).factOrigin !== "output-helper") authorizationError("not output-helper preparation");
5136
5407
  calls.delete(call);
@@ -5337,8 +5608,37 @@ function assertAuthorizationBinding(call, binding) {
5337
5608
  authorizationError("request/runtime/model/scope binding mismatch");
5338
5609
  }
5339
5610
  }
5611
+ function targetOutputAccess(access) {
5612
+ return (access.rowAccess === "read" || access.rowAccess === "list") && access.outputAccess === access.rowAccess && access.virtualAccess === access.rowAccess && access.docPermissionsAccess === access.rowAccess;
5613
+ }
5340
5614
  function queryOutputAccess(access) {
5341
- return (access.operation === "read" || access.operation === "list") && (access.rowAccess === "read" || access.rowAccess === "list") && access.outputAccess === access.rowAccess && access.virtualAccess === access.rowAccess && access.docPermissionsAccess === access.rowAccess;
5615
+ return (access.operation === "read" || access.operation === "list") && targetOutputAccess(access);
5616
+ }
5617
+ function writeBranchAccess(access, operation, branch) {
5618
+ return access.operation === operation && access.rowAccess === (branch === "update" ? "update" : void 0) && access.virtualAccess === branch && access.outputAccess === "read" && access.docPermissionsAccess === branch;
5619
+ }
5620
+ function resolveWriteServiceAuthorization(input, origin) {
5621
+ if (!["create", "update", "upsert"].includes(origin) || input.parent || scope(input.binding).length || (origin === "create" ? input.applicability !== "create" : origin === "update" ? input.applicability !== "mutation" : input.applicability !== "mutation" && input.applicability !== "service") || !writeBranchAccess(input.access, origin, origin === "create" ? "create" : "update"))
5622
+ authorizationError("invalid write entry origin");
5623
+ const call = resolveServiceAuthorization(input);
5624
+ storeCallRecord(call, { ...callRecord(call), writeOrigin: origin });
5625
+ return call;
5626
+ }
5627
+ function deriveWriteOutputAuthorization(parent, binding, branch) {
5628
+ assertAuthorizationBinding(parent, binding);
5629
+ const record3 = callRecord(parent);
5630
+ if (!record3.writeOrigin || record3.writeOutputBranch || scope(binding).length || record3.writeOrigin !== "upsert" && record3.writeOrigin !== branch || !writeBranchAccess(record3.access, record3.writeOrigin, branch))
5631
+ authorizationError("invalid write output origin/branch");
5632
+ const call = Object.freeze(/* @__PURE__ */ Object.create(null));
5633
+ storeCallRecord(call, {
5634
+ ...record3,
5635
+ writeOrigin: void 0,
5636
+ writeOutputBranch: branch,
5637
+ sourceMode: record3.configuration[branch === "create" ? "createAuthorizationMode" : "updateAuthorizationMode"] ?? "isolated",
5638
+ fieldPolicyOwner: void 0,
5639
+ view: void 0
5640
+ });
5641
+ return call;
5342
5642
  }
5343
5643
  function deriveQueryAuthorization(input) {
5344
5644
  if (!input.parent || !input.snapshotDerivation) return;
@@ -5369,9 +5669,9 @@ function deriveQueryAuthorization(input) {
5369
5669
  const configuration = target?.configuration ?? parent.configuration;
5370
5670
  const relatedTargets = target ? target.relatedTargets ?? [] : parent.relatedTargets;
5371
5671
  const policy = target ? parent.policy.related[target.path] ?? copyAuthorizationValue(normalizePolicy(void 0, "service", configuration, relatedTargets)) : parent.policy;
5372
- const queryOrigin = edge.kind === "related" ? parent.queryOrigin && queryOutputAccess(access) ? access.rowAccess : void 0 : parent.queryOrigin;
5672
+ const queryOrigin = edge.kind === "related" ? parent.queryOrigin && queryOutputAccess(access) || parent.writeOutputBranch && targetOutputAccess(access) ? access.rowAccess : void 0 : parent.queryOrigin;
5373
5673
  const call = Object.freeze(/* @__PURE__ */ Object.create(null));
5374
- calls.set(call, {
5674
+ storeCallRecord(call, {
5375
5675
  binding: Object.freeze({ ...input.binding, scopePath: Object.freeze([...scope(input.binding)]) }),
5376
5676
  access,
5377
5677
  configuration,
@@ -5385,6 +5685,7 @@ function deriveQueryAuthorization(input) {
5385
5685
  permissions: parent.permissions,
5386
5686
  provenance: parent.provenance,
5387
5687
  queryOrigin,
5688
+ writeOutputBranch: parent.writeOutputBranch,
5388
5689
  sourceMode: edge.kind === "related" ? modeFor(configuration, queryOrigin) : parent.sourceMode,
5389
5690
  factOrigin: edge.kind === "embedded" ? parent.factOrigin : "document",
5390
5691
  fieldPolicyOwner: target ? call : parent.fieldPolicyOwner ?? input.parent,
@@ -5397,8 +5698,8 @@ function modeFor(configuration, origin) {
5397
5698
  }
5398
5699
  function resolveServiceAuthorization(input) {
5399
5700
  if (input.parent) {
5400
- const parent = callRecord(input.parent).binding;
5401
- if (parent.request !== input.binding.request || parent.runtime !== input.binding.runtime)
5701
+ const parent2 = callRecord(input.parent).binding;
5702
+ if (parent2.request !== input.binding.request || parent2.runtime !== input.binding.runtime)
5402
5703
  authorizationError("derived call request/runtime mismatch");
5403
5704
  }
5404
5705
  const permissions = input.parent ? callRecord(input.parent).permissions : captureAuthorizationPermissions(input.requestPermissions, input.applicability === "output");
@@ -5423,13 +5724,16 @@ function resolveServiceAuthorization(input) {
5423
5724
  if (part.includes(".")) authorizationError("scopePath requires response segments");
5424
5725
  }
5425
5726
  if (input.parent) {
5426
- const parent = callRecord(input.parent).binding;
5427
- if (parent.request !== input.binding.request || parent.runtime !== input.binding.runtime) {
5727
+ const parent2 = callRecord(input.parent).binding;
5728
+ if (parent2.request !== input.binding.request || parent2.runtime !== input.binding.runtime) {
5428
5729
  authorizationError("derived call request/runtime mismatch");
5429
5730
  }
5430
5731
  }
5732
+ const parent = input.parent ? callRecord(input.parent) : void 0;
5733
+ const writeOrigin = parent?.writeOrigin === "upsert" && !parent.writeOutputBranch && input.snapshotDerivation?.kind === "retry" && input.applicability === "create" && !scope(input.binding).length && writeBranchAccess(parent.access, "upsert", "update") && writeBranchAccess(access, "upsert", "create") ? "upsert" : void 0;
5734
+ if (writeOrigin) assertAuthorizationBinding(input.parent, input.binding);
5431
5735
  const call = Object.freeze(/* @__PURE__ */ Object.create(null));
5432
- calls.set(call, {
5736
+ storeCallRecord(call, {
5433
5737
  binding: Object.freeze({ ...input.binding, scopePath: Object.freeze(scopePath) }),
5434
5738
  access,
5435
5739
  configuration,
@@ -5440,6 +5744,7 @@ function resolveServiceAuthorization(input) {
5440
5744
  permissions,
5441
5745
  provenance: input.parent ? callRecord(input.parent).provenance : call,
5442
5746
  queryOrigin,
5747
+ writeOrigin,
5443
5748
  sourceMode,
5444
5749
  factOrigin: !input.parent && input.applicability === "output" ? "output-helper" : "document",
5445
5750
  fieldPolicyOwner: void 0,
@@ -5470,6 +5775,10 @@ function readServiceAuthorizationMode(call, binding) {
5470
5775
  assertAuthorizationBinding(call, binding);
5471
5776
  return callRecord(call).sourceMode;
5472
5777
  }
5778
+ function isWriteOutputAuthorization(call, binding) {
5779
+ assertAuthorizationBinding(call, binding);
5780
+ return callRecord(call).writeOutputBranch !== void 0;
5781
+ }
5473
5782
  function isOutputHelperAuthorization(call, binding) {
5474
5783
  assertAuthorizationBinding(call, binding);
5475
5784
  return callRecord(call).factOrigin === "output-helper";
@@ -5541,7 +5850,7 @@ init_authorization_snapshot();
5541
5850
  init_logger_helpers();
5542
5851
  init_authorization_snapshot();
5543
5852
  init_output_work_ledger();
5544
- import { types as types8 } from "util";
5853
+ import { types as types10 } from "util";
5545
5854
  var protectedKeys = /* @__PURE__ */ new Set([
5546
5855
  "__proto__",
5547
5856
  "constructor",
@@ -5559,7 +5868,7 @@ owned.add(EMPTY_DOCUMENT_GRANTS);
5559
5868
  function normalizeDocumentGrants(value, metadataField = "_permissions") {
5560
5869
  debitOutputWork();
5561
5870
  if (typeof metadataField !== "string") authorizationError("invalid document permission field");
5562
- if (value === null || typeof value !== "object" || types8.isProxy(value))
5871
+ if (value === null || typeof value !== "object" || types10.isProxy(value))
5563
5872
  authorizationError("document grants must be a plain boolean record");
5564
5873
  if (owned.has(value)) {
5565
5874
  if (Object.hasOwn(value, metadataField)) authorizationError("protected document grant key");
@@ -5586,7 +5895,7 @@ function normalizeDocumentGrants(value, metadataField = "_permissions") {
5586
5895
  return facts;
5587
5896
  }
5588
5897
  function documentGrantsFromMetadata(value, metadataField) {
5589
- if (value === null || typeof value !== "object" || types8.isProxy(value))
5898
+ if (value === null || typeof value !== "object" || types10.isProxy(value))
5590
5899
  return normalizeDocumentGrants(value, metadataField);
5591
5900
  const slots = Object.getOwnPropertyDescriptors(value);
5592
5901
  delete slots._view;
@@ -5599,7 +5908,7 @@ async function invokeDocumentPermissions(args) {
5599
5908
  try {
5600
5909
  box = await args.gate.run(() => {
5601
5910
  const value = args.invoke();
5602
- return types8.isPromise(value) ? Promise.prototype.then.call(value, (result2) => ({ value: result2 })) : { value };
5911
+ return types10.isPromise(value) ? Promise.prototype.then.call(value, (result2) => ({ value: result2 })) : { value };
5603
5912
  });
5604
5913
  } catch (error2) {
5605
5914
  if (args.preserveControlledErrors && error2 instanceof ServiceAuthorizationError) throw error2;
@@ -5784,7 +6093,7 @@ function admitDocumentStage(call, binding, input, owning, inheritedSource = fals
5784
6093
  let prepared;
5785
6094
  if (owning && inheritedSource) {
5786
6095
  const parent = stageRecord(owning.stage);
5787
- if (!input || typeof input !== "object" || types9.isProxy(input) || Object.getPrototypeOf(input) !== Object.prototype && Object.getPrototypeOf(input) !== null)
6096
+ if (!input || typeof input !== "object" || types11.isProxy(input) || Object.getPrototypeOf(input) !== Object.prototype && Object.getPrototypeOf(input) !== null)
5788
6097
  authorizationError("embedded source must be an ordinary projected document");
5789
6098
  if (parent.borrowed && !isBorrowableAuthorizationRecord(input))
5790
6099
  authorizationError("unsupported borrowed embedded source");
@@ -5899,7 +6208,7 @@ function resolveDocumentStage(stage, resolve, exposeSource = true) {
5899
6208
  source,
5900
6209
  getAuthorizationPermissions(record3.call, record3.binding)
5901
6210
  );
5902
- if (types9.isPromise(value)) {
6211
+ if (types11.isPromise(value)) {
5903
6212
  void value.then((facts) => {
5904
6213
  try {
5905
6214
  commit(facts);
@@ -5983,7 +6292,7 @@ function memoizeStageFieldDecision(stage, binding, key, evaluate) {
5983
6292
  };
5984
6293
  try {
5985
6294
  const value = evaluate.call(record3.binding.request, getAuthorizationPermissions(authorization, binding), grants);
5986
- if (types9.isPromise(value)) {
6295
+ if (types11.isPromise(value)) {
5987
6296
  const promise = pendingFieldDecision(decision);
5988
6297
  track(promise);
5989
6298
  void value.then((result2) => {
@@ -6025,19 +6334,44 @@ function copyDocumentView(value, budget = createTrustedOutputBudget()) {
6025
6334
  return materializeTrustedOutputValue(value, "", budget, { keep: () => true });
6026
6335
  }
6027
6336
  var sources = /* @__PURE__ */ new WeakMap();
6028
- var originals = /* @__PURE__ */ new WeakMap();
6029
6337
  var referenceOriginals = /* @__PURE__ */ new WeakMap();
6030
6338
  function getQueryOutputOriginal(input, call) {
6031
- return input && typeof input === "object" && call && sources.get(input)?.has(call) ? originals.get(input) ?? input : input;
6032
- }
6033
- function getQueryReferenceOriginal(input) {
6034
- return referenceOriginals.get(input);
6339
+ return input && typeof input === "object" && call ? sources.get(input)?.get(call)?.original ?? input : input;
6340
+ }
6341
+ function getQueryReferenceOriginal(input, publication) {
6342
+ const origins = referenceOriginals.get(input);
6343
+ const originals = publication ? origins?.owners.get(publication) : origins?.originals;
6344
+ return originals?.size === 1 ? originals.keys().next().value : void 0;
6345
+ }
6346
+ function retainReferenceOrigin(input, original, publication) {
6347
+ let origins = referenceOriginals.get(input);
6348
+ if (!origins) {
6349
+ origins = { owners: /* @__PURE__ */ new WeakMap(), originals: /* @__PURE__ */ new Map() };
6350
+ referenceOriginals.set(input, origins);
6351
+ }
6352
+ let owned2 = origins.owners.get(publication);
6353
+ if (!owned2) origins.owners.set(publication, owned2 = /* @__PURE__ */ new Map());
6354
+ owned2.set(original, (owned2.get(original) ?? 0) + 1);
6355
+ origins.originals.set(original, (origins.originals.get(original) ?? 0) + 1);
6356
+ }
6357
+ function releaseReferenceOrigin(input, original, publication) {
6358
+ const origins = referenceOriginals.get(input);
6359
+ const owned2 = origins.owners.get(publication);
6360
+ const release = (counts) => {
6361
+ const count = counts.get(original);
6362
+ if (count === 1) counts.delete(original);
6363
+ else counts.set(original, count - 1);
6364
+ };
6365
+ release(owned2);
6366
+ if (!owned2.size) origins.owners.delete(publication);
6367
+ release(origins.originals);
6368
+ if (!origins.originals.size) referenceOriginals.delete(input);
6035
6369
  }
6036
- function captureReferenceOrigins(original, normalized, paths, budget) {
6370
+ function captureReferenceOrigins(original, normalized, paths, budget, retain) {
6037
6371
  const storage2 = (value) => value instanceof Document3 ? value._doc : value;
6038
6372
  const walk = (raw, copy, parts, index, depth) => {
6039
6373
  visitTrustedOutput(budget, depth);
6040
- if (!raw || !copy || typeof raw !== "object" || typeof copy !== "object" || types9.isProxy(raw) || types9.isProxy(copy))
6374
+ if (!raw || !copy || typeof raw !== "object" || typeof copy !== "object" || types11.isProxy(raw) || types11.isProxy(copy))
6041
6375
  return;
6042
6376
  if (Array.isArray(raw) && Array.isArray(copy)) {
6043
6377
  visitTrustedOutput(budget, depth, copy.length);
@@ -6048,7 +6382,7 @@ function captureReferenceOrigins(original, normalized, paths, budget) {
6048
6382
  return;
6049
6383
  }
6050
6384
  if (index === parts.length) {
6051
- if (raw !== copy && isBorrowableAuthorizationRecord(copy)) referenceOriginals.set(copy, raw);
6385
+ if (raw !== copy && isBorrowableAuthorizationRecord(copy)) retain(copy, raw);
6052
6386
  return;
6053
6387
  }
6054
6388
  const a = Object.getOwnPropertyDescriptor(storage2(raw), parts[index]), b = Object.getOwnPropertyDescriptor(copy, parts[index]);
@@ -6060,40 +6394,49 @@ function prepareQueryOutputSource(call, binding, input) {
6060
6394
  assertAuthorizationBinding(call, binding);
6061
6395
  assertOutputPublication(outputPublicationFor(call));
6062
6396
  const existing = input && typeof input === "object" ? sources.get(input)?.get(call) : void 0;
6063
- if (existing) return existing;
6064
- if (!input || typeof input !== "object" || types9.isProxy(input)) authorizationError("unsupported output source");
6397
+ if (existing) return existing.prepared;
6398
+ if (!input || typeof input !== "object" || types11.isProxy(input)) authorizationError("unsupported output source");
6399
+ const writeOutput = isWriteOutputAuthorization(call, binding);
6400
+ const publication = outputPublicationFor(call);
6065
6401
  let raw = input;
6066
6402
  if (input instanceof Document3) {
6067
6403
  try {
6068
6404
  raw = outsideOutputWorkLedger(() => input.toObject({ virtuals: false, flattenMaps: true }));
6069
6405
  } catch {
6406
+ if (writeOutput) {
6407
+ const error2 = new ServiceAuthorizationError("write output conversion failed");
6408
+ failOutputPublication(publication, error2);
6409
+ throw error2;
6410
+ }
6070
6411
  raw = input._doc;
6071
6412
  }
6072
6413
  }
6073
- const borrowed = readServiceAuthorizationMode(call, binding) === "trusted" && isBorrowableAuthorizationRecord(raw);
6074
- const publication = outputPublicationFor(call);
6075
- const source = borrowed ? raw : copyDocumentView(raw, createPublicationRowBudget(publication));
6414
+ const borrowed = readServiceAuthorizationMode(call, binding) === "trusted" && (writeOutput || isBorrowableAuthorizationRecord(raw));
6415
+ const source = writeOutput || !borrowed ? copyDocumentView(raw, createPublicationRowBudget(publication)) : raw;
6076
6416
  assertOutputPublication(outputPublicationFor(call));
6077
- if (!borrowed && (!source || typeof source !== "object" || Object.getPrototypeOf(source) !== Object.prototype && Object.getPrototypeOf(source) !== null))
6417
+ if ((writeOutput || !borrowed) && (!source || typeof source !== "object" || Object.getPrototypeOf(source) !== Object.prototype && Object.getPrototypeOf(source) !== null))
6078
6418
  authorizationError("output source must be an ordinary projected document");
6079
6419
  const prepared = { source, borrowed };
6080
6420
  let captures2 = sources.get(source);
6081
6421
  if (!captures2) sources.set(source, captures2 = /* @__PURE__ */ new WeakMap());
6082
- captures2.set(call, prepared);
6083
- if (publicationOutputLedger(publication))
6084
- retainPublicationResource(publication, () => {
6085
- captures2.delete(call);
6086
- originals.delete(source);
6087
- referenceOriginals.delete(source);
6088
- });
6422
+ captures2.set(call, { prepared, original: input });
6423
+ const references = [];
6424
+ retainPublicationResource(publication, () => {
6425
+ captures2.delete(call);
6426
+ for (const [key, original] of references) releaseReferenceOrigin(key, original, publication);
6427
+ references.length = 0;
6428
+ });
6089
6429
  if (source !== input) {
6090
- originals.set(source, input);
6091
6430
  if (!isOutputHelperAuthorization(call, binding))
6092
6431
  captureReferenceOrigins(
6093
6432
  input,
6094
6433
  source,
6095
6434
  readServiceOutputPolicy(call, binding).catalog.referencePaths ?? [],
6096
- createTrustedOutputBudget()
6435
+ createTrustedOutputBudget(),
6436
+ (key, original) => {
6437
+ retainReferenceOrigin(key, original, publication);
6438
+ references.push([key, original]);
6439
+ }
6097
6440
  );
6098
6441
  }
6099
6442
  return prepared;
@@ -6158,53 +6501,7 @@ init_concurrency();
6158
6501
 
6159
6502
  // src/acl/populate-access.ts
6160
6503
  import JsonRouter4 from "@web-ts-toolkit/express-json-router";
6161
-
6162
- // src/operation-access.ts
6163
- var OPERATION_ACCESS_VARIANTS = {
6164
- list: { basic: "basicList", advanced: "advancedList" },
6165
- read: { basic: "basicRead", advanced: "advancedRead" },
6166
- create: { basic: "basicCreate", advanced: "advancedCreate" },
6167
- update: { basic: "basicUpdate", advanced: "advancedUpdate" },
6168
- upsert: { basic: "basicUpsert", advanced: "advancedUpsert" },
6169
- count: { basic: "basicCount", advanced: "advancedCount" },
6170
- distinct: { basic: "basicDistinct", advanced: "advancedDistinct" }
6171
- };
6172
- var reservedVariantAccesses = new Set(
6173
- Object.values(OPERATION_ACCESS_VARIANTS).flatMap(({ basic, advanced }) => [basic, advanced])
6174
- );
6175
- var isRouteVariantAccess = (access) => typeof access === "string" && reservedVariantAccesses.has(access);
6176
- var isPairedRouteAccess = (access) => Object.hasOwn(OPERATION_ACCESS_VARIANTS, access);
6177
- async function resolveRouteOperationAccess({
6178
- baseAccess,
6179
- variant,
6180
- getExactOption,
6181
- isAllowedBase,
6182
- canActivate,
6183
- subdocuments = false
6184
- }) {
6185
- let access = baseAccess;
6186
- if (subdocuments) {
6187
- const keys2 = access.split(".");
6188
- const operation = keys2[2];
6189
- if (keys2.length === 3 && keys2[0] === "subs" && keys2[1] !== "" && (operation === "list" || operation === "read")) {
6190
- const field = keys2[1];
6191
- const fieldKey = `operationAccess.subs.${field}`;
6192
- const variantGuard2 = getExactOption(`${fieldKey}.${OPERATION_ACCESS_VARIANTS[operation][variant]}`);
6193
- if (variantGuard2 !== void 0) return canActivate(variantGuard2);
6194
- const baseGuard = getExactOption(`${fieldKey}.${operation}`);
6195
- if (baseGuard !== void 0) return canActivate(baseGuard);
6196
- const fieldGuard = getExactOption(fieldKey);
6197
- if (fieldGuard !== void 0) return canActivate(fieldGuard);
6198
- access = operation;
6199
- }
6200
- }
6201
- if (!isPairedRouteAccess(access)) return isAllowedBase(access);
6202
- const variantGuard = getExactOption(`operationAccess.${OPERATION_ACCESS_VARIANTS[access][variant]}`);
6203
- if (variantGuard !== void 0) return canActivate(variantGuard);
6204
- return isAllowedBase(access);
6205
- }
6206
-
6207
- // src/acl/populate-access.ts
6504
+ init_operation_access();
6208
6505
  var PopulateAccessError = class extends JsonRouter4.clientErrors.BadRequestError {
6209
6506
  constructor(access) {
6210
6507
  const errors = [{ detail: `Route-only access ${access} cannot be used for populate` }];
@@ -6213,7 +6510,10 @@ var PopulateAccessError = class extends JsonRouter4.clientErrors.BadRequestError
6213
6510
  }
6214
6511
  };
6215
6512
  function assertPopulateAccess(access) {
6216
- if (isRouteVariantAccess(access)) throw new PopulateAccessError(access);
6513
+ if (typeof access !== "string") return;
6514
+ const keys2 = access.split(".");
6515
+ if (isRemovedOperationAccess(access) || isOperationAccessMemberPath(access) || keys2[0] === "subs" && isRemovedOperationAccess(keys2[2]))
6516
+ throw new PopulateAccessError(access);
6217
6517
  }
6218
6518
 
6219
6519
  // src/services/base.ts
@@ -6223,7 +6523,7 @@ init_trusted_output_materialization();
6223
6523
  init_authorization_snapshot();
6224
6524
 
6225
6525
  // src/acl/document-guard.ts
6226
- import { types as types10 } from "util";
6526
+ import { types as types12 } from "util";
6227
6527
  init_authorization_snapshot();
6228
6528
  init_trusted_output_materialization();
6229
6529
  init_helpers();
@@ -6241,7 +6541,7 @@ function captureCondition(input) {
6241
6541
  const copy = (value, depth) => {
6242
6542
  visitTrustedOutput(budget, depth);
6243
6543
  if (typeof value === "string") return value;
6244
- if (!value || typeof value !== "object" || types10.isProxy(value) || !Array.isArray(value))
6544
+ if (!value || typeof value !== "object" || types12.isProxy(value) || !Array.isArray(value))
6245
6545
  authorizationError("document condition must contain only strings and arrays");
6246
6546
  if (Object.getPrototypeOf(value) !== Array.prototype || active.has(value))
6247
6547
  authorizationError("unsupported document condition array");
@@ -6296,11 +6596,47 @@ function getServiceExecutors(receiver) {
6296
6596
  return registered;
6297
6597
  }
6298
6598
  function createServiceExecution(receiver, access, authorization, applicability = "service", relatedTargets = [], parent, configuration, requestPermissions, hydration = access.operation === "list" ? "find" : "findOne", snapshotDerivation) {
6599
+ return prepareServiceExecution(
6600
+ receiver,
6601
+ access,
6602
+ authorization,
6603
+ applicability,
6604
+ relatedTargets,
6605
+ parent,
6606
+ configuration,
6607
+ requestPermissions,
6608
+ hydration,
6609
+ snapshotDerivation
6610
+ );
6611
+ }
6612
+ function createWriteServiceExecution(receiver, operation, authorization, applicability = operation === "create" ? "create" : "mutation", relatedTargets = []) {
6613
+ const branch = operation === "create" ? "create" : "update";
6614
+ return prepareServiceExecution(
6615
+ receiver,
6616
+ {
6617
+ operation,
6618
+ ...branch === "update" ? { rowAccess: "update" } : {},
6619
+ virtualAccess: branch,
6620
+ outputAccess: "read",
6621
+ docPermissionsAccess: branch
6622
+ },
6623
+ authorization,
6624
+ applicability,
6625
+ relatedTargets,
6626
+ void 0,
6627
+ void 0,
6628
+ void 0,
6629
+ "findOne",
6630
+ void 0,
6631
+ operation
6632
+ );
6633
+ }
6634
+ function prepareServiceExecution(receiver, access, authorization, applicability, relatedTargets, parent, configuration, requestPermissions, hydration, snapshotDerivation, writeOrigin) {
6299
6635
  const registered = getServiceExecutors(receiver);
6300
6636
  const receiving = registered.binding();
6301
6637
  const binding = Object.freeze({ ...receiving, scopePath: Object.freeze([...receiving.scopePath ?? []]) });
6302
6638
  const permissions = requestPermissions ?? registered.permissions();
6303
- const call = resolveServiceAuthorization({
6639
+ const input = {
6304
6640
  binding,
6305
6641
  access,
6306
6642
  authorization,
@@ -6312,7 +6648,8 @@ function createServiceExecution(receiver, access, authorization, applicability =
6312
6648
  listResponse: access.operation === "list" && parent === void 0,
6313
6649
  readResponse: access.operation === "read" && parent === void 0,
6314
6650
  snapshotDerivation
6315
- });
6651
+ };
6652
+ const call = writeOrigin ? resolveWriteServiceAuthorization(input, writeOrigin) : resolveServiceAuthorization(input);
6316
6653
  const execution = Object.freeze(/* @__PURE__ */ Object.create(null));
6317
6654
  const publication = parent && snapshotDerivation?.kind === "related" ? outputPublicationFor(parent) : createOutputPublication();
6318
6655
  bindOutputPublication(call, publication);
@@ -6327,11 +6664,26 @@ function createServiceExecution(receiver, access, authorization, applicability =
6327
6664
  access: readServiceAuthorizationAccess(call, binding),
6328
6665
  family: execution,
6329
6666
  purpose: Object.freeze({ kind: "dto" }),
6667
+ writeOrigin,
6330
6668
  hydration: resolveHydration(readServiceAuthorizationHydration(call, binding), hydration)
6331
6669
  })
6332
6670
  );
6333
6671
  return execution;
6334
6672
  }
6673
+ function deriveWriteOutputExecution(receiver, parent, branch) {
6674
+ const record3 = readServiceExecution(receiver, parent);
6675
+ if (!record3.writeOrigin || record3.purpose.kind !== "dto" || outputPublicationFor(record3.authorization) !== record3.publication)
6676
+ authorizationError("invalid write output purpose/publication");
6677
+ assertOutputPublication(record3.publication);
6678
+ const call = deriveWriteOutputAuthorization(record3.authorization, record3.binding, branch);
6679
+ bindOutputPublication(call, record3.publication);
6680
+ const execution = Object.freeze(/* @__PURE__ */ Object.create(null));
6681
+ executions.set(
6682
+ execution,
6683
+ Object.freeze({ ...record3, authorization: call, ownsPublication: false, writeOrigin: void 0 })
6684
+ );
6685
+ return execution;
6686
+ }
6335
6687
  function withExecutionDocumentCondition(receiver, parent, condition) {
6336
6688
  assertDocumentConditionReceiver(receiver);
6337
6689
  const record3 = readServiceExecution(receiver, parent);
@@ -7014,7 +7366,7 @@ init_runtime_context();
7014
7366
  import { AsyncLocalStorage as AsyncLocalStorage5 } from "async_hooks";
7015
7367
  init_populate_policy2();
7016
7368
  init_authorization_snapshot();
7017
- import { types as types11 } from "util";
7369
+ import { types as types13 } from "util";
7018
7370
  var cores = /* @__PURE__ */ new WeakMap();
7019
7371
  var outputHelperServices = /* @__PURE__ */ new WeakMap();
7020
7372
  function ownValue(receiver, key) {
@@ -7022,9 +7374,9 @@ function ownValue(receiver, key) {
7022
7374
  return slot && "value" in slot ? slot.value : void 0;
7023
7375
  }
7024
7376
  function assertOutputHelperCoreOwner(receiver) {
7025
- if (!receiver || types11.isProxy(receiver)) authorizationError("invalid output-helper Core receiver");
7377
+ if (!receiver || types13.isProxy(receiver)) authorizationError("invalid output-helper Core receiver");
7026
7378
  const owner = cores.get(receiver);
7027
- if (!owner || ownValue(receiver, "req") !== owner.request || ownValue(receiver, "requestRuntime") !== owner.runtime || types11.isProxy(owner.request) || ownValue(owner.request, "macl") !== receiver)
7379
+ if (!owner || ownValue(receiver, "req") !== owner.request || ownValue(receiver, "requestRuntime") !== owner.runtime || types13.isProxy(owner.request) || ownValue(owner.request, "macl") !== receiver)
7028
7380
  authorizationError("output-helper receiving request/Core/runtime mismatch");
7029
7381
  return owner;
7030
7382
  }
@@ -7032,7 +7384,7 @@ function registerOutputHelperServiceOwner(receiver, owner, modelName) {
7032
7384
  outputHelperServices.set(receiver, { ...owner, modelName, model: owner.runtime.getModelInstance(modelName) });
7033
7385
  }
7034
7386
  function assertOutputHelperServiceOwner(receiver) {
7035
- if (!receiver || types11.isProxy(receiver)) authorizationError("invalid output-helper service receiver");
7387
+ if (!receiver || types13.isProxy(receiver)) authorizationError("invalid output-helper service receiver");
7036
7388
  const owner = outputHelperServices.get(receiver);
7037
7389
  if (!owner || ownValue(receiver, "req") !== owner.request || ownValue(receiver, "requestCore") !== owner.core || ownValue(receiver, "requestRuntime") !== owner.runtime || ownValue(receiver, "modelName") !== owner.modelName)
7038
7390
  authorizationError("output-helper receiving service mismatch");
@@ -7287,10 +7639,13 @@ function castCountGroups(input, values) {
7287
7639
  init_public_admission();
7288
7640
 
7289
7641
  // src/acl/model-output-planning.ts
7642
+ init_operation_access();
7290
7643
  init_manager();
7291
7644
  init_field_catalog();
7292
7645
  init_authorization_snapshot();
7293
7646
  init_authorization_modes();
7647
+ init_document_permissions_definition();
7648
+ init_persisted_dependencies();
7294
7649
  init_virtual_populate_dependencies();
7295
7650
 
7296
7651
  // src/acl/output-helper-options.ts
@@ -7327,7 +7682,7 @@ function normalizeOutputAuthorizationOptions(input, options, purpose) {
7327
7682
  // src/acl/output-projection.ts
7328
7683
  init_authorization_snapshot();
7329
7684
  init_field_catalog();
7330
- import { types as types12 } from "util";
7685
+ import { types as types14 } from "util";
7331
7686
 
7332
7687
  // src/acl/output-selection.ts
7333
7688
  init_query();
@@ -7603,10 +7958,12 @@ function prepareExistingOutputShape(authorization, binding, source) {
7603
7958
 
7604
7959
  // src/acl/output-projection.ts
7605
7960
  init_virtual_populate_dependencies();
7961
+ init_document_permissions_definition();
7606
7962
 
7607
7963
  // src/acl/virtual-projection.ts
7964
+ init_document_permissions_definition();
7608
7965
  init_query();
7609
- import { get as get6, isArray as isArray7, isPlainObject as isPlainObject17 } from "@web-ts-toolkit/utils";
7966
+ import { get as get6, isPlainObject as isPlainObject17 } from "@web-ts-toolkit/utils";
7610
7967
  init_virtual_descriptor();
7611
7968
  init_virtual_populate_dependencies();
7612
7969
  var getScopedPermissionSchema = (root, scopePath) => {
@@ -7615,19 +7972,6 @@ var getScopedPermissionSchema = (root, scopePath) => {
7615
7972
  const scoped = get6(root, scopePath.join("."));
7616
7973
  return isPlainObject17(scoped) ? scoped : null;
7617
7974
  };
7618
- var resolveAlwaysSelectForAccess = (raw, access) => {
7619
- if (!raw) return [];
7620
- if (isArray7(raw)) return [...raw];
7621
- if (isPlainObject17(raw)) {
7622
- const record3 = raw;
7623
- const exact = record3[access];
7624
- if (isArray7(exact)) return [...exact];
7625
- const def = record3.default;
7626
- if (isArray7(def)) return [...def];
7627
- return [];
7628
- }
7629
- return [];
7630
- };
7631
7975
  var stripVirtualsFromNormalizedSelect = (normalized, virtualNames) => normalized.filter((token) => {
7632
7976
  const base = token.startsWith("-") ? token.slice(1) : token;
7633
7977
  if (base.includes(".sub.")) return false;
@@ -7673,11 +8017,10 @@ function planVirtualProjection(args) {
7673
8017
  scopePath
7674
8018
  );
7675
8019
  const modelPermissionPrefix = snapshot.modelPermissionPrefix ?? "";
7676
- const rawAlways = scopePath.length > 0 ? [] : resolveAlwaysSelectForAccess(snapshot.alwaysSelectFields, outputAccess);
7677
- const alwaysStripped = stripVirtualsFromNormalizedSelect(
7678
- normalizeSelect(rawAlways),
7679
- dbVirtualPaths
7680
- ).filter((t) => !t.startsWith("-") && !t.includes(".sub."));
8020
+ const hookInputs = scopePath.length > 0 ? [] : resolveDocumentPermissionsDefinition(snapshot.docPermissions, docPermissionsAccess)?.dependsOn ?? [];
8021
+ const hookInputsStripped = stripVirtualsFromNormalizedSelect([...hookInputs], dbVirtualPaths).filter(
8022
+ (t) => !t.startsWith("-") && !t.includes(".sub.")
8023
+ );
7681
8024
  const persistedDefined = scopedPermissionSchema ? Object.keys(scopedPermissionSchema).filter((k) => !registrySet.has(k) && k !== "sub") : [];
7682
8025
  let outputPersisted;
7683
8026
  if (selectionMode === "all") {
@@ -7748,7 +8091,7 @@ function planVirtualProjection(args) {
7748
8091
  if (isPersistedFetchable(f)) fetchSet.add(f);
7749
8092
  }
7750
8093
  for (const d of depRelative) fetchSet.add(d);
7751
- for (const f of alwaysStripped) fetchSet.add(f);
8094
+ for (const f of hookInputsStripped) fetchSet.add(f);
7752
8095
  for (const f of joinFields.filter((t) => !t.startsWith("-"))) fetchSet.add(stripLeadingDash(f));
7753
8096
  for (const f of [...baseFields, ...identityFields]) {
7754
8097
  const leaf = stripLeadingDash(f);
@@ -7763,7 +8106,7 @@ function planVirtualProjection(args) {
7763
8106
  );
7764
8107
  const internalOnly = /* @__PURE__ */ new Set([
7765
8108
  ...virtualOnlyDeps,
7766
- ...alwaysStripped.filter((f) => !outputPersistedSet.has(f)),
8109
+ ...hookInputsStripped.filter((f) => !outputPersistedSet.has(f)),
7767
8110
  ...joinFields.filter((f) => !outputPersistedSet.has(stripLeadingDash(f)))
7768
8111
  ]);
7769
8112
  if (outputIdExcluded) internalOnly.add("_id");
@@ -7972,14 +8315,9 @@ function expandCatalogProjection(args, selection, safeDefinitions) {
7972
8315
  const internal = args.internalFetch ?? {};
7973
8316
  const { fetchIdRetained, outputIdExcluded } = shape;
7974
8317
  const identity = fetchIdRetained ? ["_id"] : [];
7975
- const always = scope2.length ? [] : [
7976
- .../* @__PURE__ */ new Set([
7977
- ...resolveAlwaysSelectForAccess(snapshot.alwaysSelectFields, outputAccess),
7978
- ...resolveAlwaysSelectForAccess(snapshot.alwaysSelectFields, docPermissionsAccess)
7979
- ])
7980
- ];
8318
+ const hookInputs = scope2.length ? [] : resolveDocumentPermissionsDefinition(snapshot.docPermissions, docPermissionsAccess)?.dependsOn ?? [];
7981
8319
  const joins = [...internal.joinFields ?? [], ...internal.extraPersistedFields ?? []];
7982
- const forced = [...always, ...joins, ...internal.baseFields ?? identity, ...internal.identityFields ?? []];
8320
+ const forced = [...hookInputs, ...joins, ...internal.baseFields ?? identity, ...internal.identityFields ?? []];
7983
8321
  const fetchSafe = (path) => isSafeOutputPath(path) && !virtual(full(path));
7984
8322
  const dependencies = Object.keys(depProvenance).filter(fetchSafe);
7985
8323
  const childFetch = Object.entries(children).flatMap(([name, child]) => {
@@ -8060,21 +8398,39 @@ function readCapturedAuthorizationOption(root, path, fallback) {
8060
8398
  return value === void 0 ? fallback : value;
8061
8399
  }
8062
8400
  function getCapturedAuthorizationOption(configuration, key) {
8063
- const defaultValue = key.startsWith("operationAccess.") ? readCapturedAuthorizationOption(configuration.operationAccessDefaults, key.slice("operationAccess.".length)) : void 0;
8401
+ const defaultValue = configuration.operationAccess === void 0 && key.startsWith("operationAccess.") ? readCapturedAuthorizationOption(configuration.operationAccessDefaults, key.slice("operationAccess.".length)) : void 0;
8064
8402
  return resolveNestedOption(
8065
8403
  (path, fallback) => readCapturedAuthorizationOption(configuration, path, fallback),
8066
8404
  key,
8067
8405
  defaultValue
8068
8406
  );
8069
8407
  }
8408
+ function selectCapturedOperationAccessGuard(configuration, access) {
8409
+ return selectOperationAccessGuard({
8410
+ ...createOperationAccessReaders(configuration, { operationAccess: configuration.operationAccessDefaults }),
8411
+ baseAccess: access,
8412
+ subdocuments: true
8413
+ });
8414
+ }
8070
8415
  function captureModelAuthorizationConfiguration(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime)) {
8071
8416
  options ??= runtime.getModelOptions(modelName);
8072
8417
  assertAuthorizationModeOptions(options, true);
8073
8418
  const readAuthorizationMode = options.readAuthorizationMode ?? "isolated";
8074
8419
  const listAuthorizationMode = options.listAuthorizationMode ?? "isolated";
8420
+ const createAuthorizationMode = options.createAuthorizationMode ?? "isolated";
8421
+ const updateAuthorizationMode = options.updateAuthorizationMode ?? "isolated";
8075
8422
  const model = runtime.getModelInstance(modelName);
8076
8423
  if (!model) return authorizationError(`unknown receiving model: ${modelName}`);
8077
8424
  const virtuals = options.virtuals;
8425
+ const docPermissions = captureDocumentPermissionsDefinition(options.docPermissions, {
8426
+ storedFields: collectPersistedTopLevel(model.schema),
8427
+ virtualNames: /* @__PURE__ */ new Set([
8428
+ ...Object.keys(model.schema.virtuals ?? {}),
8429
+ ...Object.entries(virtuals ?? {}).filter(
8430
+ ([, value]) => value !== void 0 && !(value && typeof value === "object" && Object.hasOwn(value, "sub"))
8431
+ ).map(([name]) => name)
8432
+ ])
8433
+ });
8078
8434
  return captureAuthorizationConfiguration({
8079
8435
  catalog: captureAuthorizationFieldCatalog(model.schema, virtuals, options.documentPermissionField),
8080
8436
  virtualPopulateSnapshot: captureVirtualPopulateSnapshot(
@@ -8087,24 +8443,25 @@ function captureModelAuthorizationConfiguration(runtime, modelName, options, pop
8087
8443
  ...resolvePopulatePolicy(options, populatePolicyDefaults),
8088
8444
  permissionSchema: options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema,
8089
8445
  virtuals,
8090
- alwaysSelectFields: options.alwaysSelectFields,
8091
8446
  modelPermissionPrefix: options.modelPermissionPrefix,
8092
8447
  requireExplicitSelect: options.requireExplicitSelect,
8093
8448
  documentPermissionField: options.documentPermissionField,
8094
- docPermissions: options.docPermissions,
8449
+ docPermissions,
8095
8450
  exposedDocPermissionKeys: options.exposedDocPermissionKeys,
8096
8451
  stripPermissionsField: options.stripPermissionsField,
8097
- disableFieldPermissions: options.disableFieldPermissions,
8452
+ disableFieldPermissions: options.disableFieldPermissions ?? true,
8098
8453
  readAuthorizationMode,
8099
8454
  listAuthorizationMode,
8455
+ createAuthorizationMode,
8456
+ updateAuthorizationMode,
8100
8457
  overrideFilter: options.overrideFilter,
8101
8458
  baseFilter: options.baseFilter,
8102
8459
  idField: options.idField,
8103
8460
  resolveIdFilter: options.resolveIdFilter,
8104
8461
  operationAccess: options.operationAccess,
8105
- // A defined stored parent (including {}) wins over exact runtime defaults.
8106
- // Keep only operation fallback data; resolve each access without a live lookup.
8107
- operationAccessDefaults: options.operationAccess === void 0 ? runtime.getDefaultModelOption("operationAccess") : void 0,
8462
+ // Keep same-owner raw defaults separately for exact field specificity. The shared
8463
+ // selector decides which paths apply; a defined operation object is never deep-merged.
8464
+ operationAccessDefaults: runtime.getDefaultModelOption("operationAccess"),
8108
8465
  hydration: options.hydration,
8109
8466
  defaults: options.defaults
8110
8467
  });
@@ -8116,7 +8473,7 @@ function captureOutputHelperConfiguration(runtime, modelName) {
8116
8473
  const modelPermissionPrefix = runtime.getExactModelOption(modelName, "modelPermissionPrefix");
8117
8474
  const exposedDocPermissionKeys = runtime.getExactModelOption(modelName, "exposedDocPermissionKeys");
8118
8475
  const stripPermissionsField = runtime.getExactModelOption(modelName, "stripPermissionsField");
8119
- const disableFieldPermissions = runtime.getExactModelOption(modelName, "disableFieldPermissions");
8476
+ const disableFieldPermissions = runtime.getExactModelOption(modelName, "disableFieldPermissions") ?? true;
8120
8477
  const permissionSchema = runtime.getExactModelOption(modelName, "permissionSchema");
8121
8478
  const virtuals = runtime.getExactModelOption(modelName, "virtuals");
8122
8479
  return captureAuthorizationConfiguration({
@@ -8409,7 +8766,7 @@ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, populat
8409
8766
  kind: entry.op === "count" ? "count" : "output",
8410
8767
  configuration,
8411
8768
  queryIntent,
8412
- operationGuard: getCapturedAuthorizationOption(configuration, `operationAccess.${entry.op}`),
8769
+ operationGuard: selectCapturedOperationAccessGuard(configuration, entry.op),
8413
8770
  relatedTargets: captureRelatedTargets(
8414
8771
  runtime,
8415
8772
  entry.model,
@@ -8458,7 +8815,7 @@ import {
8458
8815
  castArray,
8459
8816
  arrayToRecord,
8460
8817
  hasOwn as hasOwn2,
8461
- isArray as isArray8,
8818
+ isArray as isArray7,
8462
8819
  isBoolean as isBoolean2,
8463
8820
  isEmpty as isEmpty2,
8464
8821
  isFunction as isFunction3,
@@ -8467,7 +8824,7 @@ import {
8467
8824
  } from "@web-ts-toolkit/utils";
8468
8825
  import { isDeepStrictEqual } from "util";
8469
8826
  function isAndFilter(filter2) {
8470
- return !!filter2 && isPlainObject18(filter2) && Object.keys(filter2).length === 1 && isArray8(filter2.$and);
8827
+ return !!filter2 && isPlainObject18(filter2) && Object.keys(filter2).length === 1 && isArray7(filter2.$and);
8471
8828
  }
8472
8829
  function isMergeableClause(filter2) {
8473
8830
  return !!filter2 && isPlainObject18(filter2) && Object.keys(filter2).every((key) => !key.startsWith("$"));
@@ -8487,7 +8844,7 @@ function optimizeAndFilter(clausesInput) {
8487
8844
  const dedupeKey = (value) => {
8488
8845
  if (value instanceof RegExp) return `regexp:${JSON.stringify([value.source, value.flags])}`;
8489
8846
  if (value instanceof Date) return `date:${value.getTime()}`;
8490
- if (isArray8(value)) {
8847
+ if (isArray7(value)) {
8491
8848
  const entries = Array.from(value, dedupeKey);
8492
8849
  return entries.every((entry) => entry !== void 0) ? `array:${JSON.stringify(entries)}` : void 0;
8493
8850
  }
@@ -8619,7 +8976,7 @@ async function setRequestPermissions(req) {
8619
8976
  const globalPermissions = getGlobalOption("globalPermissions");
8620
8977
  const permissions = isFunction3(globalPermissions) ? await globalPermissions.call(req, req) : void 0;
8621
8978
  if (isPlainObject18(permissions)) req[requestPermissionField] = permissions;
8622
- else if (isArray8(permissions)) req[requestPermissionField] = arrayToRecord(permissions);
8979
+ else if (isArray7(permissions)) req[requestPermissionField] = arrayToRecord(permissions);
8623
8980
  else if (isString5(permissions)) req[requestPermissionField] = { [permissions]: true };
8624
8981
  else req[requestPermissionField] = {};
8625
8982
  owners.set(requestPermissionField, activeRuntime);
@@ -8633,7 +8990,7 @@ async function evaluateRouteGuard(req, permissions, routeGuard) {
8633
8990
  if (isString5(routeGuard)) {
8634
8991
  return stringHandler(routeGuard);
8635
8992
  }
8636
- if (isArray8(routeGuard)) {
8993
+ if (isArray7(routeGuard)) {
8637
8994
  return arrayHandler(routeGuard);
8638
8995
  }
8639
8996
  if (isFunction3(routeGuard)) {
@@ -8668,7 +9025,7 @@ async function collectSchemaFields({
8668
9025
  if (value) fields.push(key);
8669
9026
  } else if (isString5(value)) {
8670
9027
  if (stringHandler(value)) fields.push(key);
8671
- } else if (isArray8(value)) {
9028
+ } else if (isArray7(value)) {
8672
9029
  if (arrayHandler(value)) fields.push(key);
8673
9030
  } else if (isFunction3(value)) {
8674
9031
  if (await value.call(req, functionArgs[0], functionArgs[1] ?? EMPTY_DOCUMENT_GRANTS)) fields.push(key);
@@ -9057,7 +9414,7 @@ function validateClientFilter(filter2) {
9057
9414
  }
9058
9415
  const blockedOperators = /* @__PURE__ */ new Set(["$where", "$expr", "$function", "$accumulator"]);
9059
9416
  const visit = (value, path) => {
9060
- if (isArray9(value)) {
9417
+ if (isArray8(value)) {
9061
9418
  value.forEach((item, index) => visit(item, `${path}[${index}]`));
9062
9419
  return;
9063
9420
  }
@@ -9122,7 +9479,7 @@ var Base = class {
9122
9479
  * Fresh output-only planner: selection stays independent of additive server authority.
9123
9480
  * Returns persisted fetch inputs including private identity/dependencies, not an output
9124
9481
  * allowlist. Document-dependent rules are deferred; no permission functions/getters run.
9125
- * Configure extra projected hook inputs with alwaysSelectFields. Omitted/undefined
9482
+ * Declare private hook inputs on docPermissions descriptors' dependsOn. Omitted/undefined
9126
9483
  * options equal {} (request-mode output); positional skipChecks/subPaths are removed.
9127
9484
  */
9128
9485
  async genSelect(access, targetFields, options = {}) {
@@ -9509,7 +9866,7 @@ var Base = class {
9509
9866
  if (!include) return docs;
9510
9867
  const includes = compact(castArray2(include));
9511
9868
  if (includes.length === 0) return docs;
9512
- const isSingle = !isArray9(docs);
9869
+ const isSingle = !isArray8(docs);
9513
9870
  let docList = (isSingle ? [docs] : docs).map(
9514
9871
  (doc) => prepareIncludeOutput(doc, parentAuthorization, parentAuthorization ? this.relatedBinding() : void 0)
9515
9872
  );
@@ -10081,7 +10438,7 @@ var Base = class {
10081
10438
  }
10082
10439
  let ret = result2.data;
10083
10440
  if (sqOptions.path) {
10084
- ret = isArray9(ret) ? flatten(ret.map((v) => get7(v, sqOptions.path))) : get7(ret, sqOptions.path);
10441
+ ret = isArray8(ret) ? flatten(ret.map((v) => get7(v, sqOptions.path))) : get7(ret, sqOptions.path);
10085
10442
  }
10086
10443
  if (sqOptions.compact) {
10087
10444
  ret = compact(castArray2(ret));
@@ -10097,12 +10454,12 @@ var Base = class {
10097
10454
 
10098
10455
  // src/services/service.ts
10099
10456
  import { Document as Document5, mongo as mongo7 } from "mongoose";
10100
- import { types as types17 } from "util";
10457
+ import { types as types19 } from "util";
10101
10458
  import {
10102
10459
  castArray as castArray3,
10103
10460
  compact as compact2,
10104
10461
  get as get10,
10105
- isArray as isArray10,
10462
+ isArray as isArray9,
10106
10463
  isBoolean as isBoolean4,
10107
10464
  isPlainObject as isPlainObject27,
10108
10465
  omit,
@@ -10223,6 +10580,7 @@ init_helpers();
10223
10580
  init_sort_policy();
10224
10581
  init_sort_policy();
10225
10582
  init_concurrency();
10583
+ init_document_permissions_definition();
10226
10584
 
10227
10585
  // src/acl/virtual-populate-execution.ts
10228
10586
  import { Document as Document4, mongo as mongo5 } from "mongoose";
@@ -10406,8 +10764,9 @@ function equivalentVirtualPopulatePredicate(left, right) {
10406
10764
  return isDeepStrictEqual2(left, right);
10407
10765
  }
10408
10766
  var readPolicy = (configuration, access) => ["operationAccess", "baseFilter", "overrideFilter"].map((key) => {
10767
+ if (key === "operationAccess") return selectCapturedOperationAccessGuard(configuration, access);
10409
10768
  const option = getCapturedAuthorizationOption(configuration, `${key}.${access}`);
10410
- return key === "operationAccess" || typeof option === "function" ? option : void 0;
10769
+ return typeof option === "function" ? option : void 0;
10411
10770
  });
10412
10771
  var compatible = (a, b) => a.binding.runtime === b.binding.runtime && a.binding.model === b.binding.model && a.binding.schema === b.binding.schema && a.access === b.access && a.requestRead === b.requestRead && a.binding.configuration.requireOperationAccessForPopulateDependencies === b.binding.configuration.requireOperationAccessForPopulateDependencies && // Different captures may share only an equivalent terminal persisted binding/policy.
10413
10772
  equivalentVirtualPopulatePredicate(
@@ -10554,7 +10913,7 @@ function targetReadAllowed(state, target) {
10554
10913
  () => evaluateRouteGuard(
10555
10914
  owner.request,
10556
10915
  owner.permissions,
10557
- getCapturedAuthorizationOption(target.configuration, "operationAccess.read")
10916
+ selectCapturedOperationAccessGuard(target.configuration, "read") ?? false
10558
10917
  )
10559
10918
  ).then(
10560
10919
  (allowed) => !!allowed,
@@ -10794,13 +11153,14 @@ async function loadVirtualPopulateOutputRows(owner, inputs, plan, publicPopulate
10794
11153
  }
10795
11154
 
10796
11155
  // src/acl/output-field-filter.ts
10797
- import { types as types15 } from "util";
11156
+ import { types as types17 } from "util";
10798
11157
  import { isPlainObject as isPlainObject23 } from "@web-ts-toolkit/utils";
10799
11158
  init_authorization_snapshot();
11159
+ init_document_permissions_definition();
10800
11160
  init_field_catalog();
10801
11161
 
10802
11162
  // src/acl/output-field-policy.ts
10803
- import { types as types13 } from "util";
11163
+ import { types as types15 } from "util";
10804
11164
  import { isPlainObject as isPlainObject22 } from "@web-ts-toolkit/utils";
10805
11165
  init_output_work_ledger();
10806
11166
  var fieldPolicies = /* @__PURE__ */ new WeakMap();
@@ -10948,7 +11308,7 @@ init_concurrency();
10948
11308
 
10949
11309
  // src/acl/output-helper-many-admission.ts
10950
11310
  init_authorization_snapshot();
10951
- import { types as types14 } from "util";
11311
+ import { types as types16 } from "util";
10952
11312
  init_field_catalog();
10953
11313
  init_output_work_ledger();
10954
11314
  var intrinsicObjectKeys = /* @__PURE__ */ new Set([
@@ -10966,7 +11326,7 @@ var intrinsicObjectKeys = /* @__PURE__ */ new Set([
10966
11326
  "toLocaleString"
10967
11327
  ]);
10968
11328
  function exactRecord(value, keys2, label) {
10969
- if (!value || typeof value !== "object" || types14.isProxy(value)) authorizationError(`invalid ${label}`);
11329
+ if (!value || typeof value !== "object" || types16.isProxy(value)) authorizationError(`invalid ${label}`);
10970
11330
  const prototype = Object.getPrototypeOf(value);
10971
11331
  if (prototype !== Object.prototype && prototype !== null) authorizationError(`invalid ${label} prototype`);
10972
11332
  for (const key of keys2)
@@ -11007,7 +11367,7 @@ function exactRecord(value, keys2, label) {
11007
11367
  return value;
11008
11368
  }
11009
11369
  function denseArray(value, maximum, label) {
11010
- if (!value || typeof value !== "object" || types14.isProxy(value)) authorizationError(`invalid ${label}`);
11370
+ if (!value || typeof value !== "object" || types16.isProxy(value)) authorizationError(`invalid ${label}`);
11011
11371
  if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype)
11012
11372
  authorizationError(`${label} must be an ordinary dense Array`);
11013
11373
  const length = Object.getOwnPropertyDescriptor(value, "length").value;
@@ -11056,8 +11416,7 @@ function admitOutputHelperRows(rows2) {
11056
11416
  init_output_work_ledger();
11057
11417
  function prepareOutputDocumentStage(authorization, binding, configuration) {
11058
11418
  const access = readServiceAuthorizationAccess(authorization, binding);
11059
- const option = getCapturedAuthorizationOption(configuration, `docPermissions.${access.docPermissionsAccess}`);
11060
- const hook = typeof option === "function" ? option : void 0;
11419
+ const hook = resolveDocumentPermissionsDefinition(configuration.docPermissions, access.docPermissionsAccess)?.get;
11061
11420
  return async (args) => {
11062
11421
  if (args.authorization !== authorization) authorizationError("document resolver call mismatch");
11063
11422
  assertAuthorizationBinding(authorization, args.binding);
@@ -11237,7 +11596,7 @@ function prepareOutputValueCopy(plan) {
11237
11596
  };
11238
11597
  }
11239
11598
  function copyAuthorizedReference(value, path, construction2, prepaid = false) {
11240
- if (value && typeof value === "object" && types15.isProxy(value))
11599
+ if (value && typeof value === "object" && types17.isProxy(value))
11241
11600
  failTrustedOutputBudget(construction2.budget, new ServiceAuthorizationError("unsupported selected proxy"));
11242
11601
  if (Array.isArray(value)) {
11243
11602
  const entries = shallowTrustedOutputArray(value, construction2.budget, construction2.depth, prepaid);
@@ -11306,7 +11665,7 @@ function continueExistingOutput(value, stage, binding, owner, accept) {
11306
11665
  readDocumentStage(stage, binding);
11307
11666
  return accept(result2);
11308
11667
  };
11309
- if (!types15.isPromise(value)) return checked(value);
11668
+ if (!types17.isPromise(value)) return checked(value);
11310
11669
  readDocumentStage(stage, binding);
11311
11670
  return trackPublicationWork(
11312
11671
  owner,
@@ -11361,7 +11720,7 @@ function filterExistingOutput(source, plan, stage, construction2, owner, prepaid
11361
11720
  const one = (value2, depth) => {
11362
11721
  readDocumentStage(stage, binding);
11363
11722
  visitTrustedOutput(construction2.budget, depth, 0);
11364
- if (value2 && typeof value2 === "object" && types15.isProxy(value2))
11723
+ if (value2 && typeof value2 === "object" && types17.isProxy(value2))
11365
11724
  failTrustedOutputBudget(construction2.budget, new ServiceAuthorizationError("unsupported selected proxy"));
11366
11725
  if (Array.isArray(value2)) {
11367
11726
  const entries = shallowTrustedOutputArray(value2, construction2.budget, depth, true);
@@ -11369,7 +11728,7 @@ function filterExistingOutput(source, plan, stage, construction2, owner, prepaid
11369
11728
  const append = (start) => {
11370
11729
  for (let index = start; index < entries.length; index++) {
11371
11730
  const value3 = one(entries[index], depth + 1);
11372
- if (types15.isPromise(value3))
11731
+ if (types17.isPromise(value3))
11373
11732
  return resume(value3, (result3) => {
11374
11733
  values.push(result3 ?? null);
11375
11734
  return append(index + 1);
@@ -11464,7 +11823,7 @@ function filterExistingOutput(source, plan, stage, construction2, owner, prepaid
11464
11823
  const walk = (start) => {
11465
11824
  for (let index = start; index < selected.length; index++) {
11466
11825
  const value = fieldValue(selected[index]);
11467
- if (types15.isPromise(value)) return resume(value, () => walk(index + 1));
11826
+ if (types17.isPromise(value)) return resume(value, () => walk(index + 1));
11468
11827
  }
11469
11828
  return finish();
11470
11829
  };
@@ -11621,7 +11980,7 @@ init_public_admission();
11621
11980
  init_document();
11622
11981
 
11623
11982
  // src/output/finalize-model-output.ts
11624
- import { types as types16 } from "util";
11983
+ import { types as types18 } from "util";
11625
11984
  import { isPlainObject as isPlainObject24 } from "@web-ts-toolkit/utils";
11626
11985
  init_trusted_output_materialization();
11627
11986
  init_authorization_snapshot();
@@ -11791,7 +12150,7 @@ async function finalizeSingleDoc(args, prepared) {
11791
12150
  const one = async (value2, childDepth, childAddress, ancestors) => {
11792
12151
  assertOutputPublication(owner);
11793
12152
  visitTrustedOutput(budget, childDepth, 0);
11794
- if (value2 && typeof value2 === "object" && types16.isProxy(value2))
12153
+ if (value2 && typeof value2 === "object" && types18.isProxy(value2))
11795
12154
  failTrustedOutputBudget(budget, new ServiceAuthorizationError("unsupported selected proxy"));
11796
12155
  if (Array.isArray(value2)) {
11797
12156
  if (ancestors.has(value2))
@@ -12230,14 +12589,12 @@ async function resolveSelectForRequest({
12230
12589
  hasPermission,
12231
12590
  functionArgs = [],
12232
12591
  mode,
12233
- alwaysSelectFields = [],
12234
12592
  virtualNames = []
12235
12593
  }) {
12236
12594
  const virtualSet = virtualNames instanceof Set ? virtualNames : new Set(virtualNames ?? []);
12237
- const strippedAlways = stripVirtuals(alwaysSelectFields ?? [], virtualSet);
12238
12595
  let normalizedSelect = stripVirtuals(normalizeSelect(targetFields), virtualSet);
12239
12596
  const persistedSchema = stripVirtualKeysFromPermissionSchema(permissionSchema, virtualSet);
12240
- if (!persistedSchema) return strippedAlways;
12597
+ if (!persistedSchema) return [];
12241
12598
  let fields = await collectSchemaFields({
12242
12599
  req,
12243
12600
  permissionSchema: persistedSchema,
@@ -12257,7 +12614,7 @@ async function resolveSelectForRequest({
12257
12614
  fields = intersection(normalizedSelect, fields.concat(excludeid ? "-_id" : "_id"));
12258
12615
  }
12259
12616
  }
12260
- return fields.concat(strippedAlways);
12617
+ return fields;
12261
12618
  }
12262
12619
  return intersection(normalizedSelect, fields);
12263
12620
  }
@@ -12285,6 +12642,7 @@ function stripVirtualKeysFromPermissionSchema(permissionSchema, virtualNames) {
12285
12642
 
12286
12643
  // src/acl/model-input-admission.ts
12287
12644
  init_authorization_snapshot();
12645
+ init_document_permissions_definition();
12288
12646
  init_field_catalog();
12289
12647
  var own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
12290
12648
  var inside = (path, root) => path === root || path.startsWith(`${root}.`);
@@ -12508,7 +12866,7 @@ async function requestInputFields(args) {
12508
12866
  }
12509
12867
  async function resolveInputDocumentGrants(args) {
12510
12868
  const { configuration } = readServiceAuthorization(args.authorization, args.binding);
12511
- const hook = getCapturedAuthorizationOption(configuration, "docPermissions.update");
12869
+ const hook = resolveDocumentPermissionsDefinition(configuration.docPermissions, "update")?.get;
12512
12870
  const access = readServiceAuthorizationAccess(args.authorization, args.binding);
12513
12871
  const context = createModelOutputContext({
12514
12872
  modelName: args.binding.modelName,
@@ -12538,10 +12896,12 @@ async function resolveInputDocumentGrants(args) {
12538
12896
  closeDocumentStage(stage, void 0, true);
12539
12897
  }
12540
12898
  }
12541
- function inputFetchPaths(catalog) {
12899
+ function inputFetchPaths(catalog, privateDependencies = []) {
12542
12900
  return [
12543
12901
  ...new Set(
12544
- (catalog.persistedPaths ?? catalog.paths).filter((p) => !p.includes("$*") && isCatalogInputPath(catalog, p))
12902
+ (catalog.persistedPaths ?? catalog.paths).filter(
12903
+ (p) => !p.includes("$*") && (isCatalogInputPath(catalog, p) || isSafeOutputPath(p) && privateDependencies.some((dep) => p === dep || p.startsWith(`${dep}.`)))
12904
+ )
12545
12905
  )
12546
12906
  ];
12547
12907
  }
@@ -12740,13 +13100,8 @@ async function subdocumentGateAllowed(service, gate) {
12740
13100
  const state = readServiceExecution(service, gate.execution);
12741
13101
  const { configuration } = readServiceAuthorization(state.authorization, state.binding);
12742
13102
  const access = state.access.rowAccess;
12743
- let guard2;
12744
- if (access.startsWith("subs.")) {
12745
- const [, sub, op] = access.split(".");
12746
- guard2 = readCapturedAuthorizationOption(configuration, `operationAccess.${access}`);
12747
- if (guard2 === void 0) guard2 = readCapturedAuthorizationOption(configuration, `operationAccess.subs.${sub}`);
12748
- if (guard2 === void 0) guard2 = getCapturedAuthorizationOption(configuration, `operationAccess.${op}`);
12749
- } else guard2 = getCapturedAuthorizationOption(configuration, `operationAccess.${access}`);
13103
+ const guard2 = selectCapturedOperationAccessGuard(configuration, access);
13104
+ if (guard2 === void 0) return false;
12750
13105
  return evaluateRouteGuard(
12751
13106
  state.binding.request,
12752
13107
  getAuthorizationPermissions(state.authorization, state.binding),
@@ -12786,6 +13141,7 @@ function subdocumentInputPolicy(service, call) {
12786
13141
  }
12787
13142
 
12788
13143
  // src/services/model-subdocument-service.ts
13144
+ init_document_permissions_definition();
12789
13145
  var denied2 = (code = "forbidden" /* Forbidden */) => ({ success: false, kind: "error", code });
12790
13146
  var invalid2 = (detail) => ({ ...denied2("bad_request" /* BadRequest */), errors: [{ detail }] });
12791
13147
  async function result(run) {
@@ -12804,16 +13160,18 @@ async function initialDenial(service, call) {
12804
13160
  if (isExecutionRowDenied(service, call.child.execution)) return denied2();
12805
13161
  if (!await initialGates(service, call)) return denied2();
12806
13162
  }
12807
- function parentSelection(service, call) {
12808
- const input = inputFetchPaths(subdocumentInputPolicy(service, call).configuration.catalog);
12809
- return [.../* @__PURE__ */ new Set(["_id", `${call.sub}._id`, ...input])].map((path) => `+${path}`).join(" ");
13163
+ function parentSelection(service, call, docPermissionsAccess) {
13164
+ const { configuration } = subdocumentInputPolicy(service, call);
13165
+ const dependencies = docPermissionsAccess ? resolveDocumentPermissionsDefinition(configuration.docPermissions, docPermissionsAccess)?.dependsOn ?? [] : [];
13166
+ const input = inputFetchPaths(configuration.catalog, dependencies);
13167
+ return [.../* @__PURE__ */ new Set(["_id", `${call.sub}._id`, ...input, ...dependencies])].map((path) => `+${path}`).join(" ");
12810
13168
  }
12811
13169
  async function mutationParent(service, id, call) {
12812
13170
  const filter2 = await subdocumentParentFilter(service, call.parent, id);
12813
13171
  if (filter2 === false) return { error: denied2("not_found" /* NotFound */) };
12814
13172
  const parent = await service.findRawParentDoc({
12815
13173
  filter: filter2,
12816
- select: parentSelection(service, call),
13174
+ select: parentSelection(service, call, ["update", "bulkUpdate"].includes(call.method) ? "update" : void 0),
12817
13175
  populate: []
12818
13176
  });
12819
13177
  return parent ? { parent } : { error: denied2("not_found" /* NotFound */) };
@@ -12865,7 +13223,7 @@ async function visibleMutationRows(service, call, parentId, rows2) {
12865
13223
  if (filter2 === false) return [];
12866
13224
  const parent = await getServiceExecutors(service).subdocumentVisibility({
12867
13225
  filter: filter2,
12868
- select: parentSelection(service, call),
13226
+ select: parentSelection(service, call, "read"),
12869
13227
  populate: []
12870
13228
  });
12871
13229
  if (!parent) return [];
@@ -12895,7 +13253,7 @@ async function listSub(service, id, sub, options) {
12895
13253
  if (childFilter === false) return denied2();
12896
13254
  const parent = await service.findRawParentDoc({
12897
13255
  filter: filter2,
12898
- select: parentSelection(service, call),
13256
+ select: parentSelection(service, call, "read"),
12899
13257
  populate: []
12900
13258
  });
12901
13259
  if (!parent) return denied2("not_found" /* NotFound */);
@@ -12918,7 +13276,7 @@ async function readSub(service, id, sub, subId, options) {
12918
13276
  const capture = subdocumentRequiresPopulateCapture(call.output, entries);
12919
13277
  const parent = await service.findRawParentDoc({
12920
13278
  filter: filter2,
12921
- select: parentSelection(service, call),
13279
+ select: parentSelection(service, call, "read"),
12922
13280
  populate: capture ? [] : entries
12923
13281
  });
12924
13282
  if (!parent) return denied2("not_found" /* NotFound */);
@@ -12972,12 +13330,12 @@ async function bulkUpdateSub(service, persist, id, sub, data, options) {
12972
13330
  const filter2 = await subdocumentRows(service, call.child, selected, selected, sub);
12973
13331
  if (filter2 === false) return denied2();
12974
13332
  const rows2 = filterCollection(get9(parent, sub), filter2);
12975
- const originals2 = rows2.map((row) => isolateDocForOutput(row));
13333
+ const originals = rows2.map((row) => isolateDocForOutput(row));
12976
13334
  const admit = await inputAdmission(service, call, parent);
12977
13335
  for (const [index, row] of rows2.entries()) {
12978
13336
  const input = findElementById(data, row._id);
12979
13337
  if (input) {
12980
- const { allowedData, allowedFields } = admit(input, originals2[index]);
13338
+ const { allowedData, allowedFields } = admit(input, originals[index]);
12981
13339
  applyUpdate(row, allowedData, allowedFields);
12982
13340
  }
12983
13341
  }
@@ -13219,7 +13577,7 @@ var Service = class extends Base {
13219
13577
  getPermissionsPosture() {
13220
13578
  return {
13221
13579
  stripPermissionsField: this.options.stripPermissionsField ?? false,
13222
- disableFieldPermissions: this.options.disableFieldPermissions ?? false
13580
+ disableFieldPermissions: this.options.disableFieldPermissions ?? true
13223
13581
  };
13224
13582
  }
13225
13583
  asServiceHookContext(context) {
@@ -13410,7 +13768,7 @@ var Service = class extends Base {
13410
13768
  };
13411
13769
  defineTrustedOutputValue(metadata, "_view", await map2("read", rowAccess.readIds?.has(id) ?? false));
13412
13770
  defineTrustedOutputValue(metadata, "_edit", await map2("update", rowAccess.updateIds?.has(id) ?? false));
13413
- } else if (!args.includePermissions) {
13771
+ } else if (!args.includePermissions && !configuration.disableFieldPermissions) {
13414
13772
  visitTrustedOutput(args.budget, metadataDepth + 1, 2);
13415
13773
  visitTrustedOutput(args.budget, metadataDepth + 2, 2);
13416
13774
  defineTrustedOutputValue(metadata, "_view", { $: "_" });
@@ -13475,13 +13833,13 @@ var Service = class extends Base {
13475
13833
  {
13476
13834
  permissionSchema: o.permissionSchema ?? null,
13477
13835
  virtuals: o.virtuals ?? null,
13478
- alwaysSelectFields: o.alwaysSelectFields ?? null,
13836
+ docPermissions: captureDocumentPermissionsDefinition(o.docPermissions),
13479
13837
  modelPermissionPrefix: o.modelPermissionPrefix ?? "",
13480
13838
  requireExplicitSelect: o.requireExplicitSelect ?? false,
13481
13839
  documentPermissionField: o.documentPermissionField ?? "_permissions",
13482
13840
  exposedDocPermissionKeys: o.exposedDocPermissionKeys,
13483
13841
  stripPermissionsField: o.stripPermissionsField ?? false,
13484
- disableFieldPermissions: o.disableFieldPermissions ?? false
13842
+ disableFieldPermissions: o.disableFieldPermissions ?? true
13485
13843
  },
13486
13844
  true
13487
13845
  );
@@ -13671,7 +14029,7 @@ var Service = class extends Base {
13671
14029
  () => evaluateRouteGuard(
13672
14030
  this.req,
13673
14031
  getAuthorizationPermissions(childState.authorization, childState.binding),
13674
- getCapturedAuthorizationOption(targetConfiguration, `operationAccess.${targetAccess}`)
14032
+ selectCapturedOperationAccessGuard(targetConfiguration, targetAccess) ?? false
13675
14033
  )
13676
14034
  ))
13677
14035
  continue;
@@ -13710,10 +14068,10 @@ var Service = class extends Base {
13710
14068
  if (value === null || value === void 0) return true;
13711
14069
  if (typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean")
13712
14070
  return true;
13713
- if (types17.isProxy(value)) return false;
14071
+ if (types19.isProxy(value)) return false;
13714
14072
  let record3 = value;
13715
14073
  for (let hops = 0; record3 && hops <= 100; hops++) {
13716
- if (types17.isProxy(record3)) return false;
14074
+ if (types19.isProxy(record3)) return false;
13717
14075
  if (record3 === mongo7.BSON.BSONValue.prototype) return true;
13718
14076
  const slot = Object.getOwnPropertyDescriptor(record3, "_bsontype");
13719
14077
  if (slot && "value" in slot) return typeof slot.value === "string";
@@ -13722,14 +14080,14 @@ var Service = class extends Base {
13722
14080
  return false;
13723
14081
  }
13724
14082
  /** Compose exact private source/public-fetch provenance; never IDs or DTO authority. */
13725
- populateTargetIdentity(value) {
13726
- const original = getQueryReferenceOriginal(value) ?? value;
14083
+ populateTargetIdentity(value, publication) {
14084
+ const original = getQueryReferenceOriginal(value, publication) ?? value;
13727
14085
  return getVirtualPopulatePublicIdentity(value) ?? getVirtualPopulatePublicIdentity(original) ?? original;
13728
14086
  }
13729
14087
  async finalizeSinglePopulateTarget(rawTarget, meta, parentOperation, parentContext, hookLimit, sharedGate, originalTarget = rawTarget, budget, publication, parentAuthorization, outputDepth = 1) {
13730
14088
  if (rawTarget === null || rawTarget === void 0) return rawTarget;
13731
14089
  if (this.isScalarPopulateValue(rawTarget)) return rawTarget;
13732
- const isDoc = !types17.isProxy(rawTarget) && (isPlainObject27(rawTarget) || rawTarget instanceof Document5);
14090
+ const isDoc = !types19.isProxy(rawTarget) && (isPlainObject27(rawTarget) || rawTarget instanceof Document5);
13733
14091
  if (!isDoc) failTrustedOutputBudget(budget, new ServiceAuthorizationError("unsupported populated target"));
13734
14092
  let cache = this.populateOutputCache.get(meta);
13735
14093
  if (!cache) {
@@ -13744,7 +14102,8 @@ var Service = class extends Base {
13744
14102
  });
13745
14103
  }
13746
14104
  const originalKey = originalTarget && typeof originalTarget === "object" ? originalTarget : rawTarget;
13747
- const cacheKey = this.populateTargetIdentity(rawTarget);
14105
+ const owner = publication ?? outputPublicationFor(meta.plan.authorization);
14106
+ const cacheKey = this.populateTargetIdentity(rawTarget, owner);
13748
14107
  const recipients = this.populateBudgetRecipients.get(meta)?.get(cacheKey);
13749
14108
  if (!recipients?.some((edge) => edge.budget === budget && edge.depth === outputDepth))
13750
14109
  authorizationError("populate target requires preregistered receiving occurrences");
@@ -13767,12 +14126,11 @@ var Service = class extends Base {
13767
14126
  docPermissionsAccess: meta.docPermissionsAccess,
13768
14127
  resolvedQuery: parentContext.resolvedQuery
13769
14128
  });
13770
- const owner = publication ?? outputPublicationFor(meta.plan.authorization);
13771
14129
  bindOutputPublication(meta.plan.authorization, owner);
13772
14130
  const selectedBudget = createReceivingOutputBudget(recipients);
13773
14131
  const pending = finalizeModelOutput({
13774
14132
  receivingModelName: meta.targetModelName,
13775
- input: parentAuthorization && readServiceAuthorizationMode(parentAuthorization, getServiceExecutors(this).binding()) === "isolated" && readServiceAuthorizationMode(meta.plan.authorization, meta.plan.authorizationBinding) === "trusted" ? copyDocumentView(rawTarget) : rawTarget,
14133
+ input: parentAuthorization && readServiceAuthorizationMode(parentAuthorization, getServiceExecutors(this).binding()) === "isolated" && readServiceAuthorizationMode(meta.plan.authorization, meta.plan.authorizationBinding) === "trusted" && !isWriteOutputAuthorization(meta.plan.authorization, meta.plan.authorizationBinding) ? copyDocumentView(rawTarget) : rawTarget,
13776
14134
  virtualAccess: meta.virtualAccess,
13777
14135
  outputAccess: meta.outputAccess,
13778
14136
  docPermissionsAccess: meta.docPermissionsAccess,
@@ -13784,7 +14142,7 @@ var Service = class extends Base {
13784
14142
  operation: parentContext.operation ?? parentOperation,
13785
14143
  publication: owner,
13786
14144
  outputBudget: selectedBudget,
13787
- virtualPopulateRow: getVirtualPopulateRow(originalKey) ?? getVirtualPopulateRow(getQueryReferenceOriginal(rawTarget) ?? rawTarget)
14145
+ virtualPopulateRow: getVirtualPopulateRow(originalKey) ?? getVirtualPopulateRow(getQueryReferenceOriginal(rawTarget, owner) ?? rawTarget)
13788
14146
  });
13789
14147
  cache.set(cacheKey, pending);
13790
14148
  const finalized = await pending;
@@ -13811,7 +14169,7 @@ var Service = class extends Base {
13811
14169
  for (const row of rows2) {
13812
14170
  const walk = (value, index, depth) => {
13813
14171
  visitTrustedOutput(row.budget, depth, 0);
13814
- if (value && typeof value === "object" && types17.isProxy(value))
14172
+ if (value && typeof value === "object" && types19.isProxy(value))
13815
14173
  failTrustedOutputBudget(row.budget, new ServiceAuthorizationError("unsupported selected proxy"));
13816
14174
  if (Array.isArray(value)) {
13817
14175
  const entries2 = shallowTrustedOutputArray(value, row.budget, depth);
@@ -13822,7 +14180,7 @@ var Service = class extends Base {
13822
14180
  if (!value || typeof value !== "object") return;
13823
14181
  if (index === parts.length) {
13824
14182
  if (this.isScalarPopulateValue(value)) return;
13825
- const key = this.populateTargetIdentity(value);
14183
+ const key = this.populateTargetIdentity(value, row.publication);
13826
14184
  const receivers = targets.get(key) ?? [];
13827
14185
  receivers.push({ budget: row.budget, depth });
13828
14186
  targets.set(key, receivers);
@@ -13876,7 +14234,7 @@ var Service = class extends Base {
13876
14234
  const slots = this.populateInputSlots.get(meta)?.get(current);
13877
14235
  if (!slots?.has(key)) authorizationError("unregistered populate source slot");
13878
14236
  child = slots.get(key);
13879
- originalChild = child && typeof child === "object" ? getQueryReferenceOriginal(child) ?? child : child;
14237
+ originalChild = child && typeof child === "object" ? getQueryReferenceOriginal(child, publication ?? outputPublicationFor(meta.plan.authorization)) ?? child : child;
13880
14238
  if (child === void 0 || child === null) {
13881
14239
  return;
13882
14240
  }
@@ -14389,7 +14747,7 @@ var Service = class extends Base {
14389
14747
  const findAssociationField = this.getAssociationFieldFromOptions(options);
14390
14748
  const withAssocSelect = findAssociationField && !finalSelect.includes(findAssociationField) ? [...finalSelect, findAssociationField] : finalSelect;
14391
14749
  const dbSelect = this.buildDbSelectForAssociation(withAssocSelect, findAssociationField);
14392
- const filteredPopulate = isArray10(withAssocSelect) && isArray10(_populate) ? _populate.filter(
14750
+ const filteredPopulate = isArray9(withAssocSelect) && isArray9(_populate) ? _populate.filter(
14393
14751
  (p) => [
14394
14752
  ...virtualPlan.publicPersistedFetchSelection,
14395
14753
  ...findAssociationField ? [findAssociationField] : []
@@ -14478,10 +14836,7 @@ var Service = class extends Base {
14478
14836
  const normalizedRequested = normalizeSelect(_select).map((t) => t.startsWith("-") ? t.slice(1) : t);
14479
14837
  const overlapsAssociation = (path) => path === findAssociationField || path.startsWith(`${findAssociationField}.`) || findAssociationField.startsWith(`${path}.`);
14480
14838
  const isDep = Object.keys(virtualPlan.depProvenance).some(overlapsAssociation);
14481
- const isHookInput = [
14482
- ...resolveAlwaysSelectForAccess(virtualSnapshot.alwaysSelectFields, virtualPlan.outputAccess),
14483
- ...resolveAlwaysSelectForAccess(virtualSnapshot.alwaysSelectFields, virtualPlan.docPermissionsAccess)
14484
- ].some(overlapsAssociation);
14839
+ const isHookInput = (resolveDocumentPermissionsDefinition(virtualSnapshot.docPermissions, virtualPlan.docPermissionsAccess)?.dependsOn ?? []).some(overlapsAssociation);
14485
14840
  const isSelected = normalizedRequested.includes(findAssociationField);
14486
14841
  if (!isDep && !isHookInput && !isSelected) {
14487
14842
  privateAssociationField = findAssociationField;
@@ -14572,13 +14927,7 @@ var Service = class extends Base {
14572
14927
  const intent = captureModelServiceIntent(this, "create", args, options);
14573
14928
  const execution = withExecutionQueryIntent(
14574
14929
  this,
14575
- createServiceExecution(
14576
- this,
14577
- { operation: "create", virtualAccess: "create", outputAccess: "read", docPermissionsAccess: "create" },
14578
- options?.authorization,
14579
- "create",
14580
- this.captureRelated(intent.args)
14581
- ),
14930
+ createWriteServiceExecution(this, "create", options?.authorization, "create", this.captureRelated(intent.args)),
14582
14931
  intent
14583
14932
  );
14584
14933
  return await executeCreate(this, execution, data, args, options, decorate);
@@ -14596,7 +14945,9 @@ var Service = class extends Base {
14596
14945
  const { populate, select } = intent.args;
14597
14946
  const { includePermissions, includeFieldPermissions, populateAccess } = intent.options;
14598
14947
  const initiatingOperation = state.access.operation;
14599
- const createPlan = this.executionOutputPlan(execution, select);
14948
+ const outputExecution = deriveWriteOutputExecution(this, execution, "create");
14949
+ const outputState = readServiceExecution(this, outputExecution);
14950
+ const createPlan = this.executionOutputPlan(outputExecution, select);
14600
14951
  const isArr = Array.isArray(data);
14601
14952
  let dataArr = isArr ? data : [data];
14602
14953
  const { maxBulkItems, maxBulkConcurrency } = this.getRequestComplexity();
@@ -14642,7 +14993,7 @@ var Service = class extends Base {
14642
14993
  }
14643
14994
  let resolvedPopulate;
14644
14995
  try {
14645
- resolvedPopulate = populate ? await this.genExecutionPopulate(execution, populateAccess, populate) : [];
14996
+ resolvedPopulate = populate ? await this.genExecutionPopulate(outputExecution, populateAccess, populate) : [];
14646
14997
  } catch (error2) {
14647
14998
  const result2 = this.getClientRequestErrorResult(error2);
14648
14999
  if (result2) return result2;
@@ -14672,7 +15023,7 @@ var Service = class extends Base {
14672
15023
  validationErrors.push({ index, errors: [] });
14673
15024
  return void 0;
14674
15025
  }
14675
- } else if (isArray10(validated)) {
15026
+ } else if (isArray9(validated)) {
14676
15027
  if (validated.length > 0) {
14677
15028
  validationErrors.push({
14678
15029
  index,
@@ -14720,8 +15071,8 @@ var Service = class extends Base {
14720
15071
  contexts[index].finalDocumentSnapshot = doc.toObject({ virtuals: false });
14721
15072
  return doc;
14722
15073
  });
14723
- const detached = await this.prepareDetachedOutputRows(execution, persistedDocs, createPlan, resolvedPopulate);
14724
- const outputRows2 = this.admitOutputRows(execution, detached);
15074
+ const detached = await this.prepareDetachedOutputRows(outputExecution, persistedDocs, createPlan, resolvedPopulate);
15075
+ const outputRows2 = this.admitOutputRows(outputExecution, detached);
14725
15076
  this.registerPopulateRecipients(outputRows2, resolvedPopulate);
14726
15077
  const docs = await mapWithConcurrencyLimit(
14727
15078
  outputRows2,
@@ -14736,7 +15087,7 @@ var Service = class extends Base {
14736
15087
  initiatingOperation,
14737
15088
  hookLimit,
14738
15089
  createGate,
14739
- state.authorization,
15090
+ outputState.authorization,
14740
15091
  row.references,
14741
15092
  row.budget,
14742
15093
  row.publication
@@ -14854,15 +15205,9 @@ var Service = class extends Base {
14854
15205
  const intent = captureModelServiceIntent(this, "updateOne", args, options);
14855
15206
  const execution = withExecutionQueryIntent(
14856
15207
  this,
14857
- createServiceExecution(
15208
+ createWriteServiceExecution(
14858
15209
  this,
14859
- {
14860
- operation: "update",
14861
- rowAccess: "update",
14862
- virtualAccess: "update",
14863
- outputAccess: "read",
14864
- docPermissionsAccess: "update"
14865
- },
15210
+ "update",
14866
15211
  options?.authorization,
14867
15212
  "mutation",
14868
15213
  this.captureRelated(intent.args)
@@ -14886,11 +15231,13 @@ var Service = class extends Base {
14886
15231
  const { populate, select } = intent.args;
14887
15232
  const { includePermissions, includeFieldPermissions, populateAccess } = intent.options;
14888
15233
  const initiatingOperation = state.access.operation;
14889
- const updatePlan = this.executionOutputPlan(execution, select);
15234
+ const outputExecution = deriveWriteOutputExecution(this, execution, "update");
15235
+ const outputState = readServiceExecution(this, outputExecution);
15236
+ const updatePlan = this.executionOutputPlan(outputExecution, select);
14890
15237
  const _filter = filter2;
14891
15238
  let _populate;
14892
15239
  try {
14893
- _populate = await this.genExecutionPopulate(execution, populateAccess, populate);
15240
+ _populate = await this.genExecutionPopulate(outputExecution, populateAccess, populate);
14894
15241
  } catch (error2) {
14895
15242
  const result2 = this.getClientRequestErrorResult(error2);
14896
15243
  if (result2) return result2;
@@ -14904,11 +15251,13 @@ var Service = class extends Base {
14904
15251
  this.completeOp("updateOne", startedAt, "forbidden" /* Forbidden */, _filter);
14905
15252
  return { success: false, kind: "error", code: "forbidden" /* Forbidden */, query };
14906
15253
  }
15254
+ const hookInputs = resolveDocumentPermissionsDefinition(captured.configuration.docPermissions, updatePlan.docPermissionsAccess)?.dependsOn ?? [];
14907
15255
  let doc = await this.model.findOne({
14908
15256
  filter: _filter,
14909
- select: uniq2([...updatePlan.persistedFetchSelection, ...inputFetchPaths(captured.configuration.catalog)]).map(
14910
- (path) => `+${path}`
14911
- )
15257
+ select: uniq2([
15258
+ ...updatePlan.persistedFetchSelection,
15259
+ ...inputFetchPaths(captured.configuration.catalog, hookInputs)
15260
+ ]).map((path) => `+${path}`)
14912
15261
  });
14913
15262
  if (!doc) {
14914
15263
  this.completeOp("updateOne", startedAt, "not_found" /* NotFound */, _filter);
@@ -14950,7 +15299,7 @@ var Service = class extends Base {
14950
15299
  this.completeOp("updateOne", startedAt, "bad_request" /* BadRequest */, _filter);
14951
15300
  return { success: false, kind: "error", code: "bad_request" /* BadRequest */ };
14952
15301
  }
14953
- } else if (isArray10(validated)) {
15302
+ } else if (isArray9(validated)) {
14954
15303
  if (validated.length > 0) {
14955
15304
  this.completeOp("updateOne", startedAt, "bad_request" /* BadRequest */, _filter);
14956
15305
  return { success: false, kind: "error", code: "bad_request" /* BadRequest */, errors: validated };
@@ -14980,8 +15329,8 @@ var Service = class extends Base {
14980
15329
  context.finalDocumentSnapshot = doc.toObject({ virtuals: false });
14981
15330
  this.asServiceHookContext(context).diff(doc);
14982
15331
  await this.changes(doc.toObject({ virtuals: false }), context);
14983
- const [detached] = await this.prepareDetachedOutputRows(execution, [doc], updatePlan, _populate);
14984
- const [row] = this.admitOutputRows(execution, [detached]);
15332
+ const [detached] = await this.prepareDetachedOutputRows(outputExecution, [doc], updatePlan, _populate);
15333
+ const [row] = this.admitOutputRows(outputExecution, [detached]);
14985
15334
  this.registerPopulateRecipients([row], _populate);
14986
15335
  if (_populate) {
14987
15336
  const updateHookLimit = this.getVirtualHookConcurrencyLimit();
@@ -14993,7 +15342,7 @@ var Service = class extends Base {
14993
15342
  initiatingOperation,
14994
15343
  updateHookLimit,
14995
15344
  updateGate,
14996
- state.authorization,
15345
+ outputState.authorization,
14997
15346
  row.references,
14998
15347
  row.budget,
14999
15348
  row.publication
@@ -15029,15 +15378,9 @@ var Service = class extends Base {
15029
15378
  const { skim, includePermissions, includeFieldPermissions, populateAccess } = intent.options;
15030
15379
  const execution = withExecutionQueryIntent(
15031
15380
  this,
15032
- createServiceExecution(
15381
+ createWriteServiceExecution(
15033
15382
  this,
15034
- {
15035
- operation: "update",
15036
- rowAccess: "update",
15037
- virtualAccess: "update",
15038
- outputAccess: "read",
15039
- docPermissionsAccess: "update"
15040
- },
15383
+ "update",
15041
15384
  options?.authorization,
15042
15385
  "mutation",
15043
15386
  this.captureRelated(intent.args)
@@ -15077,19 +15420,7 @@ var Service = class extends Base {
15077
15420
  );
15078
15421
  const execution = withExecutionQueryIntent(
15079
15422
  this,
15080
- createServiceExecution(
15081
- this,
15082
- {
15083
- operation: "upsert",
15084
- rowAccess: "update",
15085
- virtualAccess: "update",
15086
- outputAccess: "read",
15087
- docPermissionsAccess: "update"
15088
- },
15089
- options?.authorization,
15090
- "mutation",
15091
- related
15092
- ),
15423
+ createWriteServiceExecution(this, "upsert", options?.authorization, "mutation", related),
15093
15424
  updateIntent
15094
15425
  );
15095
15426
  const { populate, select } = updateIntent.args;
@@ -15989,15 +16320,9 @@ var PublicService = class extends Service {
15989
16320
  const intent = upsertId ? captureModelServiceIntent(this, "updateOne", { ...updateArgs, select: effectiveSelect }, updateOptions) : captureModelServiceIntent(this, "create", createArgs, createOptions);
15990
16321
  const execution = withExecutionQueryIntent(
15991
16322
  this,
15992
- createServiceExecution(
16323
+ createWriteServiceExecution(
15993
16324
  this,
15994
- {
15995
- operation: "upsert",
15996
- rowAccess: "update",
15997
- virtualAccess: "update",
15998
- outputAccess: "read",
15999
- docPermissionsAccess: "update"
16000
- },
16325
+ "upsert",
16001
16326
  requestOnlyServiceOptions({}).authorization,
16002
16327
  "service",
16003
16328
  this.captureRelated(intent.args)
@@ -16087,7 +16412,7 @@ var PublicService = class extends Service {
16087
16412
  captureListFallbackAdmission(execution) {
16088
16413
  const { authorization, binding } = readServiceExecution(this, execution);
16089
16414
  const { configuration } = readServiceAuthorization(authorization, binding);
16090
- const guard2 = getCapturedAuthorizationOption(configuration, "operationAccess.list");
16415
+ const guard2 = selectCapturedOperationAccessGuard(configuration, "list");
16091
16416
  const permissions = getAuthorizationPermissions(authorization, binding);
16092
16417
  return () => getRequestWorkState(this.req, this.requestRuntime).hookGate.run(
16093
16418
  () => withCapturedModelOperationGuard(
@@ -16373,7 +16698,7 @@ init_helpers();
16373
16698
 
16374
16699
  // src/processors.ts
16375
16700
  init_permissions_alias();
16376
- import { cloneDeep as cloneDeep5, forEach as forEach5, get as get11, hasOwn as hasOwn3, isArray as isArray11, isPlainObject as isPlainObject28, map, set as set9 } from "@web-ts-toolkit/utils";
16701
+ import { cloneDeep as cloneDeep5, forEach as forEach5, get as get11, hasOwn as hasOwn3, isArray as isArray10, isPlainObject as isPlainObject28, map, set as set9 } from "@web-ts-toolkit/utils";
16377
16702
  function cloneProcessorValue(value) {
16378
16703
  const copy = cloneDeep5(value);
16379
16704
  copyPermissionsAliasGraph(value, copy);
@@ -16416,7 +16741,7 @@ function resolveLeafParents(obj, src) {
16416
16741
  if (!isPlainObject28(target)) return ret;
16417
16742
  const targetObject = target;
16418
16743
  const next = targetObject[seg];
16419
- if (isArray11(next)) {
16744
+ if (isArray10(next)) {
16420
16745
  for (const item of next) {
16421
16746
  ret.push(item);
16422
16747
  }
@@ -16432,11 +16757,11 @@ function resolveLeafParents(obj, src) {
16432
16757
  });
16433
16758
  return pairs;
16434
16759
  }
16435
- var copyAndDepopulate = (docObject, operations, options = { mutable: true, idField: "_id" }) => {
16760
+ var copyAndDepopulate = (docObject, operations2, options = { mutable: true, idField: "_id" }) => {
16436
16761
  const mutable = options.mutable !== false;
16437
16762
  const idField = options.idField ?? "_id";
16438
16763
  const obj = mutable ? docObject : cloneProcessorValue(docObject);
16439
- forEach5(Array.isArray(operations) ? operations : [], (op) => {
16764
+ forEach5(Array.isArray(operations2) ? operations2 : [], (op) => {
16440
16765
  if (!op || typeof op.src !== "string" || typeof op.dest !== "string") return;
16441
16766
  const src = op.src;
16442
16767
  const dest = op.dest;
@@ -16453,7 +16778,7 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
16453
16778
  const leaf = targetObject[seg];
16454
16779
  const sourceForDest = leaf;
16455
16780
  let depopulated;
16456
- if (isArray11(leaf)) {
16781
+ if (isArray10(leaf)) {
16457
16782
  if (leaf.length === 0) {
16458
16783
  depopulated = [];
16459
16784
  } else if (leaf.every((item) => isPlainObject28(item))) {
@@ -16483,7 +16808,7 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
16483
16808
  if (!isPlainObject28(target)) return ret;
16484
16809
  const targetObject = target;
16485
16810
  const next = targetObject[seg];
16486
- if (isArray11(next)) {
16811
+ if (isArray10(next)) {
16487
16812
  for (const item of next) {
16488
16813
  ret.push(item);
16489
16814
  }
@@ -16495,10 +16820,10 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
16495
16820
  });
16496
16821
  return obj;
16497
16822
  };
16498
- var copyPaths = (docObject, operations, options = { mutable: true }) => {
16823
+ var copyPaths = (docObject, operations2, options = { mutable: true }) => {
16499
16824
  const mutable = options.mutable !== false;
16500
16825
  const obj = mutable ? docObject : cloneProcessorValue(docObject);
16501
- forEach5(Array.isArray(operations) ? operations : [], (op) => {
16826
+ forEach5(Array.isArray(operations2) ? operations2 : [], (op) => {
16502
16827
  if (!op || typeof op.src !== "string" || typeof op.dest !== "string") return;
16503
16828
  const src = op.src;
16504
16829
  const dest = op.dest;
@@ -16513,10 +16838,10 @@ var copyPaths = (docObject, operations, options = { mutable: true }) => {
16513
16838
  });
16514
16839
  return obj;
16515
16840
  };
16516
- var movePaths = (docObject, operations, options = { mutable: true }) => {
16841
+ var movePaths = (docObject, operations2, options = { mutable: true }) => {
16517
16842
  const mutable = options.mutable !== false;
16518
16843
  const obj = mutable ? docObject : cloneProcessorValue(docObject);
16519
- forEach5(Array.isArray(operations) ? operations : [], (op) => {
16844
+ forEach5(Array.isArray(operations2) ? operations2 : [], (op) => {
16520
16845
  if (!op || typeof op.src !== "string" || typeof op.dest !== "string") return;
16521
16846
  const src = op.src;
16522
16847
  const dest = op.dest;
@@ -16534,12 +16859,12 @@ var movePaths = (docObject, operations, options = { mutable: true }) => {
16534
16859
  });
16535
16860
  return obj;
16536
16861
  };
16537
- var sliceArrays = (docObject, operations, options = { mutable: true, maxSlice: DEFAULT_MAX_SLICE }) => {
16862
+ var sliceArrays = (docObject, operations2, options = { mutable: true, maxSlice: DEFAULT_MAX_SLICE }) => {
16538
16863
  const mutable = options.mutable !== false;
16539
16864
  const maxSlice = options.maxSlice ?? DEFAULT_MAX_SLICE;
16540
16865
  assertNonNegativeSafeInteger(maxSlice, "maxSlice", "sliceArrays");
16541
16866
  const obj = mutable ? docObject : cloneProcessorValue(docObject);
16542
- forEach5(Array.isArray(operations) ? operations : [], (op) => {
16867
+ forEach5(Array.isArray(operations2) ? operations2 : [], (op) => {
16543
16868
  if (!op || typeof op.src !== "string") return;
16544
16869
  const src = op.src;
16545
16870
  if (src.length === 0) return;
@@ -16558,7 +16883,7 @@ var sliceArrays = (docObject, operations, options = { mutable: true, maxSlice: D
16558
16883
  }
16559
16884
  forEach5(resolveLeafParents(obj, src), ({ parent, leaf }) => {
16560
16885
  const leafValue = parent[leaf];
16561
- if (!isArray11(leafValue)) return;
16886
+ if (!isArray10(leafValue)) return;
16562
16887
  const end = typeof limit === "undefined" ? void 0 : skip + limit;
16563
16888
  const window = leafValue.slice(skip, end);
16564
16889
  if (typeof rawDest === "undefined") {
@@ -16570,10 +16895,10 @@ var sliceArrays = (docObject, operations, options = { mutable: true, maxSlice: D
16570
16895
  });
16571
16896
  return obj;
16572
16897
  };
16573
- var countPaths = (docObject, operations, options = { mutable: true }) => {
16898
+ var countPaths = (docObject, operations2, options = { mutable: true }) => {
16574
16899
  const mutable = options.mutable !== false;
16575
16900
  const obj = mutable ? docObject : cloneProcessorValue(docObject);
16576
- forEach5(Array.isArray(operations) ? operations : [], (op) => {
16901
+ forEach5(Array.isArray(operations2) ? operations2 : [], (op) => {
16577
16902
  if (!op || typeof op.src !== "string" || typeof op.dest !== "string") return;
16578
16903
  const src = op.src;
16579
16904
  const dest = op.dest;
@@ -16584,7 +16909,7 @@ var countPaths = (docObject, operations, options = { mutable: true }) => {
16584
16909
  if (!hasOwn3(parent, leaf)) return;
16585
16910
  const leafValue = parent[leaf];
16586
16911
  let count;
16587
- if (isArray11(leafValue)) {
16912
+ if (isArray10(leafValue)) {
16588
16913
  count = leafValue.length;
16589
16914
  } else if (isPlainObject28(leafValue)) {
16590
16915
  count = Object.keys(leafValue).length;
@@ -16598,10 +16923,10 @@ var countPaths = (docObject, operations, options = { mutable: true }) => {
16598
16923
  });
16599
16924
  return obj;
16600
16925
  };
16601
- var maskPaths = (docObject, operations, options = { mutable: true }) => {
16926
+ var maskPaths = (docObject, operations2, options = { mutable: true }) => {
16602
16927
  const mutable = options.mutable !== false;
16603
16928
  const obj = mutable ? docObject : cloneProcessorValue(docObject);
16604
- forEach5(Array.isArray(operations) ? operations : [], (op) => {
16929
+ forEach5(Array.isArray(operations2) ? operations2 : [], (op) => {
16605
16930
  if (!op || typeof op.src !== "string") return;
16606
16931
  const src = op.src;
16607
16932
  if (src.length === 0) return;
@@ -16653,6 +16978,8 @@ async function initializeAclRequest({
16653
16978
  // src/core.ts
16654
16979
  init_runtime();
16655
16980
  init_runtime_context();
16981
+ init_operation_access();
16982
+ init_document_permissions_definition();
16656
16983
  init_authorization_snapshot();
16657
16984
  init_document();
16658
16985
  var emptyPermissionLeaf = () => ({ $: "_" });
@@ -16867,7 +17194,7 @@ var Core = class {
16867
17194
  this,
16868
17195
  refModelName,
16869
17196
  populateAccess,
16870
- getCapturedAuthorizationOption(targetConfiguration, `operationAccess.${populateAccess}`),
17197
+ selectCapturedOperationAccessGuard(targetConfiguration, populateAccess),
16871
17198
  permissions,
16872
17199
  () => this.isAllowed(refModelName, populateAccess)
16873
17200
  )) {
@@ -16879,13 +17206,10 @@ var Core = class {
16879
17206
  populateAccess,
16880
17207
  ret.select
16881
17208
  );
16882
- const hookInputs = resolveAlwaysSelectForAccess(
16883
- targetConfiguration.alwaysSelectFields,
16884
- populateAccess
16885
- );
17209
+ const hookInputs = resolveDocumentPermissionsDefinition(targetConfiguration.docPermissions, populateAccess)?.dependsOn ?? [];
16886
17210
  ret.select = uniq3([
16887
17211
  ...ret.select,
16888
- ...stripVirtuals(hookInputs, [...targetConfiguration.catalog.virtualPaths ?? []])
17212
+ ...stripVirtuals([...hookInputs], [...targetConfiguration.catalog.virtualPaths ?? []])
16889
17213
  ]);
16890
17214
  const match = isString6(p) ? {} : p.match ?? {};
16891
17215
  const filter2 = await resolveAccessFilterForRequest({
@@ -16953,7 +17277,7 @@ var Core = class {
16953
17277
  if (isFunction6(validate)) {
16954
17278
  const permissions = this.getGlobalPermissions();
16955
17279
  return validate.call(this.req, allowedData, permissions, context);
16956
- } else if (isBoolean5(validate) || isArray12(validate)) {
17280
+ } else if (isBoolean5(validate) || isArray11(validate)) {
16957
17281
  return validate;
16958
17282
  } else {
16959
17283
  return true;
@@ -17002,7 +17326,7 @@ var Core = class {
17002
17326
  /** Explicit fresh hook-to-boolean-facts utility, not document/output/row authority. */
17003
17327
  async genDocPermissions(modelName, doc, access, context) {
17004
17328
  const configuration = captureModelAuthorizationConfiguration(this.requestRuntime, modelName);
17005
- const hook = getCapturedAuthorizationOption(configuration, `docPermissions.${access}`);
17329
+ const hook = resolveDocumentPermissionsDefinition(configuration.docPermissions, access)?.get;
17006
17330
  const permissions = this.getGlobalPermissions();
17007
17331
  const diagnostic = createModelOutputContext({
17008
17332
  modelName,
@@ -17198,33 +17522,21 @@ var Core = class {
17198
17522
  async isAllowed(modelName, access) {
17199
17523
  const captured = consumeCapturedModelOperationGuard(this, modelName, access);
17200
17524
  if (captured) return evaluateRouteGuard(this.req, captured.permissions, captured.guard);
17201
- if (access.startsWith("subs")) {
17202
- const keys2 = access.split(".");
17203
- if (keys2.length < 3) {
17204
- return false;
17205
- }
17206
- const [, field, op] = keys2;
17207
- const subOption = getExactModelOption(modelName, `operationAccess.${access}`);
17208
- if (isUndefined(subOption)) {
17209
- const subFieldOption = getExactModelOption(modelName, `operationAccess.subs.${field}`);
17210
- if (isUndefined(subFieldOption)) {
17211
- const opOption = getModelOption(modelName, `operationAccess.${op}`);
17212
- return this.canActivate(opOption);
17213
- }
17214
- return this.canActivate(subFieldOption);
17215
- }
17216
- return this.canActivate(subOption);
17217
- }
17218
- const operationAccess = getModelOption(modelName, `operationAccess.${access}`);
17219
- return this.canActivate(operationAccess);
17525
+ return this.resolveOperationAccess(modelName, access);
17220
17526
  }
17221
- /** Authorize route entry using explicit server-owned basic/advanced metadata. */
17222
- async isAllowedRoute(modelName, baseAccess, variant) {
17527
+ /** Authorize entry using explicit server-owned basic/advanced/root metadata. */
17528
+ async isAllowedRoute(modelName, baseAccess, context) {
17529
+ return this.resolveOperationAccess(modelName, baseAccess, context);
17530
+ }
17531
+ /** Fresh live reads; omitted context is a base check, never an ambient entry context. */
17532
+ async resolveOperationAccess(modelName, baseAccess, context) {
17223
17533
  return resolveRouteOperationAccess({
17224
17534
  baseAccess,
17225
- variant,
17226
- getExactOption: (key) => getExactModelOption(modelName, key),
17227
- isAllowedBase: (access) => this.isAllowed(modelName, access),
17535
+ context,
17536
+ ...createOperationAccessReaders(
17537
+ this.requestRuntime.getModelOptions(modelName),
17538
+ this.requestRuntime.getDefaultModelOptions()
17539
+ ),
17228
17540
  canActivate: (guard2) => this.canActivate(guard2),
17229
17541
  subdocuments: true
17230
17542
  });
@@ -17280,10 +17592,10 @@ function guard(condition) {
17280
17592
  const { type = "param", key } = id;
17281
17593
  if (type === "param") {
17282
17594
  const paramValue = req.params[key];
17283
- _id = isArray13(paramValue) ? paramValue[0] ?? null : paramValue ?? null;
17595
+ _id = isArray12(paramValue) ? paramValue[0] ?? null : paramValue ?? null;
17284
17596
  } else if (type === "query") {
17285
17597
  const _qval = req.query[key];
17286
- if (isArray13(_qval)) _id = _qval.length > 0 ? _qval[0] : null;
17598
+ if (isArray12(_qval)) _id = _qval.length > 0 ? _qval[0] : null;
17287
17599
  else _id = _qval;
17288
17600
  } else {
17289
17601
  _id = null;
@@ -17301,7 +17613,7 @@ function guard(condition) {
17301
17613
  const { stringHandler, arrayHandler } = createValidator(phas);
17302
17614
  if (isString7(cond)) {
17303
17615
  if (stringHandler(cond)) return next();
17304
- } else if (isArray13(cond)) {
17616
+ } else if (isArray12(cond)) {
17305
17617
  if (arrayHandler(cond)) return next();
17306
17618
  } else if (isFunction7(cond)) {
17307
17619
  const result2 = await cond.call(req, permissions);
@@ -17316,7 +17628,8 @@ import express2 from "express";
17316
17628
 
17317
17629
  // src/routers/model-router.ts
17318
17630
  import JsonRouter8 from "@web-ts-toolkit/express-json-router";
17319
- import { forEach as forEach7, isPlainObject as isPlainObject31, isString as isString8, isUndefined as isUndefined2, normalizeUrlPath as normalizeUrlPath3, padEnd } from "@web-ts-toolkit/utils";
17631
+ import { forEach as forEach7, isPlainObject as isPlainObject31, isString as isString8, isUndefined, normalizeUrlPath as normalizeUrlPath3, padEnd } from "@web-ts-toolkit/utils";
17632
+ init_operation_access();
17320
17633
  init_logger_helpers();
17321
17634
  init_runtime();
17322
17635
  init_runtime_context();
@@ -18804,7 +19117,7 @@ function setModelCollectionRoutes(context) {
18804
19117
  body: defineOpenApiSchemaResolver(getAdvancedCreateOpenApiBody)
18805
19118
  });
18806
19119
  router.get("/new", async (req) => {
18807
- await context.assertAllowed(req, "new");
19120
+ await context.assertAllowed(req, "new", "basic");
18808
19121
  const svc = context.getPublicService(req);
18809
19122
  const result2 = await svc._new({}, { includePermissions: false, includeFieldPermissions: false });
18810
19123
  handleResultError(result2);
@@ -19138,7 +19451,7 @@ function setModelDocumentRoutes(context) {
19138
19451
  body: defineOpenApiSchemaResolver(getAdvancedUpsertOpenApiBody)
19139
19452
  });
19140
19453
  router.delete(`/:${options.idParam}`, async (req) => {
19141
- await context.assertAllowed(req, "delete");
19454
+ await context.assertAllowed(req, "delete", "basic");
19142
19455
  const id = parsePathParam(req.params[options.idParam], options.idParam);
19143
19456
  const svc = context.getPublicService(req);
19144
19457
  const result2 = await svc._delete(id);
@@ -19235,7 +19548,7 @@ function setModelSubDocumentRoutes(context) {
19235
19548
  body: defineOpenApiSchemaResolver(() => context.getRequestSchema("requestSchemas.subList") ?? subListBodySchema)
19236
19549
  });
19237
19550
  context.router.patch(`/:${context.options.idParam}/${sub}`, async (req) => {
19238
- await context.assertAllowed(req, `subs.${sub}.update`);
19551
+ await context.assertAllowed(req, `subs.${sub}.update`, "basic");
19239
19552
  const id = parsePathParam(req.params[context.options.idParam], context.options.idParam);
19240
19553
  const data = await parseBodyWithSchema(
19241
19554
  subMutationBodySchema,
@@ -19299,7 +19612,7 @@ function setModelSubDocumentRoutes(context) {
19299
19612
  body: defineOpenApiSchemaResolver(() => context.getRequestSchema("requestSchemas.subRead") ?? subReadBodySchema)
19300
19613
  });
19301
19614
  context.router.patch(`/:${context.options.idParam}/${sub}/:subId`, async (req) => {
19302
- await context.assertAllowed(req, `subs.${sub}.update`);
19615
+ await context.assertAllowed(req, `subs.${sub}.update`, "basic");
19303
19616
  const id = parsePathParam(req.params[context.options.idParam], context.options.idParam);
19304
19617
  const subId = parsePathParam(req.params.subId, "subId");
19305
19618
  const data = await parseBodyWithSchema(
@@ -19322,7 +19635,7 @@ function setModelSubDocumentRoutes(context) {
19322
19635
  )
19323
19636
  });
19324
19637
  context.router.post(`/:${context.options.idParam}/${sub}`, async (req) => {
19325
- await context.assertAllowed(req, `subs.${sub}.create`);
19638
+ await context.assertAllowed(req, `subs.${sub}.create`, "basic");
19326
19639
  const id = parsePathParam(req.params[context.options.idParam], context.options.idParam);
19327
19640
  const data = await parseBodyWithSchema(
19328
19641
  subMutationBodySchema,
@@ -19344,7 +19657,7 @@ function setModelSubDocumentRoutes(context) {
19344
19657
  )
19345
19658
  });
19346
19659
  context.router.delete(`/:${context.options.idParam}/${sub}/:subId`, async (req) => {
19347
- await context.assertAllowed(req, `subs.${sub}.delete`);
19660
+ await context.assertAllowed(req, `subs.${sub}.delete`, "basic");
19348
19661
  const id = parsePathParam(req.params[context.options.idParam], context.options.idParam);
19349
19662
  const subId = parsePathParam(req.params.subId, "subId");
19350
19663
  const svc = context.getPublicService(req);
@@ -19374,8 +19687,8 @@ function registerOpenApiRoute(runtime, basePath, defaultTag, route) {
19374
19687
  // src/routers/model-router.ts
19375
19688
  var clientErrors2 = JsonRouter8.clientErrors;
19376
19689
  function setOption(parentKey, optionKey, option) {
19377
- const key = isUndefined2(option) ? parentKey : `${parentKey}.${optionKey}`;
19378
- const value = isUndefined2(option) ? optionKey : option;
19690
+ const key = isUndefined(option) ? parentKey : `${parentKey}.${optionKey}`;
19691
+ const value = isUndefined(option) ? optionKey : option;
19379
19692
  assertMutableRouterOption("model", key);
19380
19693
  this.runtime.setModelOption(
19381
19694
  this.modelName,
@@ -19461,22 +19774,39 @@ var ModelRouter = class _ModelRouter {
19461
19774
  */
19462
19775
  this.documentPermissionField = setOption.bind(this, "documentPermissionField");
19463
19776
  /**
19464
- * The model fields always selected for ACL and response shaping.
19465
- */
19466
- this.alwaysSelectFields = setOption.bind(this, "alwaysSelectFields");
19467
- /**
19468
- * The function called in the process of generating document permissions.
19777
+ * Configure a callable/descriptor directly, or replace one exact/default/custom
19778
+ * access definition. Descriptor dependsOn adds private persisted inputs, not output grants.
19779
+ * An undefined access restores default fallback; pass undefined alone to clear the option.
19469
19780
  */
19470
- this.docPermissions = setOption.bind(this, "docPermissions");
19781
+ this.docPermissions = (...args) => {
19782
+ const key = args.length === 2 ? `docPermissions.${args[0]}` : "docPermissions";
19783
+ const value = args.length === 2 ? args[1] : args[0];
19784
+ assertMutableRouterOption("model", key);
19785
+ this.runtime.setModelOption(
19786
+ this.modelName,
19787
+ key,
19788
+ value
19789
+ );
19790
+ return this;
19791
+ };
19471
19792
  /**
19472
- * Configure live base and basic/advanced route guards. Only undefined inherits;
19793
+ * Configure live scalar/default and independent basic/advanced/root entry guards. Only undefined inherits;
19473
19794
  * selected false denies with HTTP 401 without removing routes or OpenAPI entries.
19474
- * `operationAccess('basicRead', false)` updates one key, and
19475
- * `operationAccess('subs.comments.basicRead', false)` updates a field-specific key.
19795
+ * `operationAccess('read.basic', false)` updates one member, and
19796
+ * `operationAccess('subs.comments.read.basic', false)` updates a field-specific member.
19476
19797
  * `operationAccess({ list: true, read: true })` replaces the whole rule object,
19477
- * not a deep merge. Use setOption with undefined to restore variant inheritance.
19798
+ * not a deep merge. Two-argument member setters accept undefined to restore fallback.
19799
+ * Updating beneath a scalar starts an object; retain the old guard in operation.default.
19478
19800
  */
19479
- this.operationAccess = setOption.bind(this, "operationAccess");
19801
+ this.operationAccess = (...args) => {
19802
+ const key = args.length === 2 ? `operationAccess.${args[0]}` : "operationAccess";
19803
+ this.runtime.setModelOption(
19804
+ this.modelName,
19805
+ key,
19806
+ args.length === 2 ? args[1] : args[0]
19807
+ );
19808
+ return this;
19809
+ };
19480
19810
  /**
19481
19811
  * The base filter definitions applied in every query transaction.
19482
19812
  * @operation `list`, `read`, `update`, `delete`
@@ -19588,6 +19918,7 @@ var ModelRouter = class _ModelRouter {
19588
19918
  }
19589
19919
  static fromModel(model, initialOptions, runtime = defaultRuntime) {
19590
19920
  assertAuthorizationModeOptions(initialOptions, true);
19921
+ assertOperationAccessOptions(initialOptions);
19591
19922
  assertNoServerModelControls(
19592
19923
  initialOptions,
19593
19924
  (detail) => {
@@ -19623,7 +19954,7 @@ var ModelRouter = class _ModelRouter {
19623
19954
  const operation = baseAccess.split(".").at(-1);
19624
19955
  const businessBody = variant !== "advanced" && ["create", "update", "upsert"].includes(operation);
19625
19956
  assertPublicAdmission(req.body, businessBody ? "data" : "envelope");
19626
- const allowed = variant === void 0 ? await req.macl.isAllowed(this.modelName, baseAccess) : await req.macl.isAllowedRoute(this.modelName, baseAccess, variant);
19957
+ const allowed = await req.macl.isAllowedRoute(this.modelName, baseAccess, variant);
19627
19958
  if (!allowed) throw new clientErrors2.UnauthorizedError();
19628
19959
  }
19629
19960
  registerOpenApiRoute(route) {
@@ -19700,7 +20031,7 @@ var ModelRouter = class _ModelRouter {
19700
20031
  }
19701
20032
  return this;
19702
20033
  }
19703
- /** Set one live option/path; `setOption('operationAccess.basicRead', undefined)` restores inheritance. */
20034
+ /** Set one live option/path; `setOption('operationAccess.read.basic', undefined)` restores fallback. */
19704
20035
  setOption(key, option) {
19705
20036
  assertMutableRouterOption("model", key);
19706
20037
  this.runtime.setModelOption(this.modelName, key, option);
@@ -19725,6 +20056,7 @@ import { isNumber as _isNumber, normalizeUrlPath as normalizeUrlPath4, orderBy a
19725
20056
  init_options();
19726
20057
  init_runtime();
19727
20058
  init_runtime_context();
20059
+ init_operation_access();
19728
20060
  var DataCore = class {
19729
20061
  constructor(req) {
19730
20062
  this.requestRuntime = getActiveRuntime() ?? defaultRuntime;
@@ -19852,16 +20184,18 @@ var DataCore = class {
19852
20184
  return evaluateRouteGuard(this.req, this.getGlobalPermissions(), routeGuard);
19853
20185
  }
19854
20186
  async isAllowed(dataName, access) {
19855
- const operationAccess = getDataOption(dataName, `operationAccess.${access}`);
19856
- return this.canActivate(operationAccess);
20187
+ return this.resolveOperationAccess(dataName, access);
19857
20188
  }
19858
- /** Authorize route entry using explicit server-owned basic/advanced metadata. */
19859
- async isAllowedRoute(dataName, baseAccess, variant) {
20189
+ /** Authorize entry using explicit server-owned basic/advanced/root metadata. */
20190
+ async isAllowedRoute(dataName, baseAccess, context) {
20191
+ return this.resolveOperationAccess(dataName, baseAccess, context);
20192
+ }
20193
+ /** Data policy has no model-default reader; base calls never select entry members. */
20194
+ async resolveOperationAccess(dataName, baseAccess, context) {
19860
20195
  return resolveRouteOperationAccess({
19861
20196
  baseAccess,
19862
- variant,
19863
- getExactOption: (key) => getExactDataOption(dataName, key),
19864
- isAllowedBase: (access) => this.isAllowed(dataName, access),
20197
+ context,
20198
+ ...createOperationAccessReaders(this.requestRuntime.getDataOptions(dataName)),
19865
20199
  canActivate: (guard2) => this.canActivate(guard2)
19866
20200
  });
19867
20201
  }
@@ -20048,22 +20382,22 @@ var RootRouter = class {
20048
20382
  }
20049
20383
  async isAllowed(req, item) {
20050
20384
  if (item.target === "data") {
20051
- return req.dacl.isAllowed(item.name, item.op);
20385
+ return req.dacl.isAllowedRoute(item.name, item.op, "root");
20052
20386
  }
20053
20387
  switch (item.op) {
20054
20388
  case "subList":
20055
- return req.macl.isAllowed(item.name, `subs.${item.sub}.list`);
20389
+ return req.macl.isAllowedRoute(item.name, `subs.${item.sub}.list`, "root");
20056
20390
  case "subRead":
20057
- return req.macl.isAllowed(item.name, `subs.${item.sub}.read`);
20391
+ return req.macl.isAllowedRoute(item.name, `subs.${item.sub}.read`, "root");
20058
20392
  case "subCreate":
20059
- return req.macl.isAllowed(item.name, `subs.${item.sub}.create`);
20393
+ return req.macl.isAllowedRoute(item.name, `subs.${item.sub}.create`, "root");
20060
20394
  case "subUpdate":
20061
20395
  case "subBulkUpdate":
20062
- return req.macl.isAllowed(item.name, `subs.${item.sub}.update`);
20396
+ return req.macl.isAllowedRoute(item.name, `subs.${item.sub}.update`, "root");
20063
20397
  case "subDelete":
20064
- return req.macl.isAllowed(item.name, `subs.${item.sub}.delete`);
20398
+ return req.macl.isAllowedRoute(item.name, `subs.${item.sub}.delete`, "root");
20065
20399
  default:
20066
- return req.macl.isAllowed(item.name, item.op);
20400
+ return req.macl.isAllowedRoute(item.name, item.op, "root");
20067
20401
  }
20068
20402
  }
20069
20403
  async processOp(req, item, index) {
@@ -20227,7 +20561,7 @@ var RootRouter = class {
20227
20561
 
20228
20562
  // src/routers/data-router.ts
20229
20563
  import JsonRouter10 from "@web-ts-toolkit/express-json-router";
20230
- import { isPlainObject as isPlainObject32, isString as isString9, isUndefined as isUndefined3, normalizeUrlPath as normalizeUrlPath5 } from "@web-ts-toolkit/utils";
20564
+ import { isPlainObject as isPlainObject32, isString as isString9, isUndefined as isUndefined2, normalizeUrlPath as normalizeUrlPath5 } from "@web-ts-toolkit/utils";
20231
20565
  init_runtime();
20232
20566
  init_helpers();
20233
20567
  init_authorization_modes();
@@ -20235,8 +20569,8 @@ init_public_admission();
20235
20569
  init_schemas();
20236
20570
  var clientErrors4 = JsonRouter10.clientErrors;
20237
20571
  function setOption2(parentKey, optionKey, option) {
20238
- const key = isUndefined3(option) ? parentKey : `${parentKey}.${optionKey}`;
20239
- const value = isUndefined3(option) ? optionKey : option;
20572
+ const key = isUndefined2(option) ? parentKey : `${parentKey}.${optionKey}`;
20573
+ const value = isUndefined2(option) ? optionKey : option;
20240
20574
  assertMutableRouterOption("data", key);
20241
20575
  this.runtime.setDataOption(this.dataName, key, value);
20242
20576
  return this;
@@ -20251,13 +20585,22 @@ var DataRouter = class {
20251
20585
  /** Base-operation field grants; basic/advanced route guards belong to operationAccess. */
20252
20586
  this.permissionSchema = setOption2.bind(this, "permissionSchema");
20253
20587
  /**
20254
- * Live list/read guards plus basicList/advancedList/basicRead/advancedRead.
20255
- * `operationAccess('basicRead', false)` updates one key and denies GET /:id
20256
- * (and HEAD) with HTTP 401; registered POST reads still inherit `read`.
20588
+ * Live scalar/default and independent basic/advanced/root list/read entry guards.
20589
+ * `operationAccess('read.basic', false)` updates one member and denies GET /:id
20590
+ * (and HEAD) with HTTP 401; registered POST reads use read.advanced then read.default.
20257
20591
  * `operationAccess({ list: true, read: true })` replaces the whole rule object,
20258
- * not a deep merge. Use setOption with undefined to restore variant inheritance.
20592
+ * not a deep merge. Two-argument member setters accept undefined to restore fallback.
20593
+ * Data never inherits model defaults; updating beneath a scalar starts an object.
20259
20594
  */
20260
- this.operationAccess = setOption2.bind(this, "operationAccess");
20595
+ this.operationAccess = (...args) => {
20596
+ const key = args.length === 2 ? `operationAccess.${args[0]}` : "operationAccess";
20597
+ this.runtime.setDataOption(
20598
+ this.dataName,
20599
+ key,
20600
+ args.length === 2 ? args[1] : args[0]
20601
+ );
20602
+ return this;
20603
+ };
20261
20604
  this.baseFilter = setOption2.bind(
20262
20605
  this,
20263
20606
  "baseFilter"
@@ -20454,7 +20797,7 @@ var DataRouter = class {
20454
20797
  }
20455
20798
  return this;
20456
20799
  }
20457
- /** Set one live option/path; `setOption('operationAccess.basicRead', undefined)` restores inheritance. */
20800
+ /** Set one live option/path; `setOption('operationAccess.read.basic', undefined)` restores fallback. */
20458
20801
  setOption(key, option) {
20459
20802
  assertMutableRouterOption("data", key);
20460
20803
  this.runtime.setDataOption(this.dataName, key, option);
@@ -20582,7 +20925,7 @@ function createRuntimeApi(runtime) {
20582
20925
  const wtt2 = runtimeMiddleware;
20583
20926
  wtt2.runtime = runtime;
20584
20927
  wtt2.createRouter = function(modelName, options) {
20585
- if (isUndefined4(options)) {
20928
+ if (isUndefined3(options)) {
20586
20929
  return new RootRouter(modelName, runtime);
20587
20930
  }
20588
20931
  assertAuthorizationModeOptions(options, true);