@web-ts-toolkit/access-router 0.61.0 → 0.62.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.js CHANGED
@@ -30,10 +30,10 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
31
 
32
32
  // src/acl/unsafe-snapshot-options.ts
33
- var unsafeSnapshotOptions;
33
+ var unsafeSnapshotCheckOptions, unsafeInitialOutputCopyOptions, unsafeSnapshotOptions;
34
34
  var init_unsafe_snapshot_options = __esm({
35
35
  "src/acl/unsafe-snapshot-options.ts"() {
36
- unsafeSnapshotOptions = [
36
+ unsafeSnapshotCheckOptions = [
37
37
  "unsafeSkipListDocumentSnapshotChecks",
38
38
  "unsafeSkipReadDocumentSnapshotChecks",
39
39
  "unsafeSkipListOutputSnapshotChecks",
@@ -41,6 +41,11 @@ var init_unsafe_snapshot_options = __esm({
41
41
  "unsafeSkipListNestedDocumentSnapshotChecks",
42
42
  "unsafeSkipReadNestedDocumentSnapshotChecks"
43
43
  ];
44
+ unsafeInitialOutputCopyOptions = [
45
+ "unsafeSkipListInitialOutputSnapshotCopy",
46
+ "unsafeSkipReadInitialOutputSnapshotCopy"
47
+ ];
48
+ unsafeSnapshotOptions = [...unsafeSnapshotCheckOptions, ...unsafeInitialOutputCopyOptions];
44
49
  }
45
50
  });
46
51
 
@@ -83,9 +88,9 @@ function assertPublicAdmission(input, kind = "envelope") {
83
88
  for (const key of ["filter", "match", "data"]) add(record3[key], "data", key);
84
89
  }
85
90
  }
86
- function assertHydrationDefaults(defaults) {
87
- if (defaults && typeof defaults === "object") {
88
- const record3 = defaults;
91
+ function assertHydrationDefaults(defaults2) {
92
+ if (defaults2 && typeof defaults2 === "object") {
93
+ const record3 = defaults2;
89
94
  if ("hydration" in record3)
90
95
  throw new TypeError("defaults.hydration is unsupported; use model hydration configuration");
91
96
  for (const bucket of [
@@ -113,11 +118,11 @@ function assertHydrationDefaults(defaults) {
113
118
  }
114
119
  }
115
120
  }
116
- function assertPublicDefaults(defaults) {
117
- assertHydrationDefaults(defaults);
118
- assertPublicAdmission(defaults);
119
- if (defaults && typeof defaults === "object") {
120
- for (const value of Object.values(defaults)) assertPublicAdmission(value);
121
+ function assertPublicDefaults(defaults2) {
122
+ assertHydrationDefaults(defaults2);
123
+ assertPublicAdmission(defaults2);
124
+ if (defaults2 && typeof defaults2 === "object") {
125
+ for (const value of Object.values(defaults2)) assertPublicAdmission(value);
121
126
  }
122
127
  }
123
128
  function pickPublicKeys(input, keys2) {
@@ -220,6 +225,37 @@ var init_hydration = __esm({
220
225
  }
221
226
  });
222
227
 
228
+ // src/options/populate-policy.ts
229
+ function isPopulatePolicyKey(key) {
230
+ return populatePolicyKeys.includes(key);
231
+ }
232
+ function normalizePopulatePolicyValue(value) {
233
+ return value === void 0 ? void 0 : value !== false;
234
+ }
235
+ function normalizePopulatePolicyOptions(options) {
236
+ const next = { ...options };
237
+ for (const key of populatePolicyKeys) {
238
+ if (key in options)
239
+ next[key] = normalizePopulatePolicyValue(options[key]);
240
+ }
241
+ return next;
242
+ }
243
+ function assertNoGlobalPopulatePolicy(key) {
244
+ if (isPopulatePolicyKey(key))
245
+ throw new TypeError(
246
+ `${key} is target-model configuration; migrate to setModelOptions(targetModelName, { ${key}: value }) or setDefaultModelOptions({ ${key}: value }) for runtime model defaults`
247
+ );
248
+ }
249
+ var populatePolicyKeys;
250
+ var init_populate_policy = __esm({
251
+ "src/options/populate-policy.ts"() {
252
+ populatePolicyKeys = [
253
+ "requireOperationAccessForPopulateQueries",
254
+ "requireOperationAccessForPopulateDependencies"
255
+ ];
256
+ }
257
+ });
258
+
223
259
  // src/helpers/collection.ts
224
260
  var import_sift, import_utils2, filterCollection, findElement, findElementById;
225
261
  var init_collection = __esm({
@@ -1335,7 +1371,7 @@ var init_logger_default = __esm({
1335
1371
  });
1336
1372
 
1337
1373
  // src/options/manager.ts
1338
- var import_utils11, toPath, cloneConfigValue, cloneForRead, freezeConfigValue, cloneAndFreezeForStore, getNestedOption, resolveNestedOption, OptionsManager;
1374
+ var import_utils11, toPath, cloneConfigValue, cloneForRead, freezeConfigValue, cloneAndFreezeForStore, cloneOptionsSnapshot, getNestedOption, resolveNestedOption, OptionsManager;
1339
1375
  var init_manager = __esm({
1340
1376
  "src/options/manager.ts"() {
1341
1377
  import_utils11 = require("@web-ts-toolkit/utils");
@@ -1399,6 +1435,7 @@ var init_manager = __esm({
1399
1435
  return value;
1400
1436
  };
1401
1437
  cloneAndFreezeForStore = (value) => freezeConfigValue(cloneForRead(value));
1438
+ cloneOptionsSnapshot = (value) => freezeConfigValue(cloneForRead(value));
1402
1439
  getNestedOption = (manager, key, defaultValue) => resolveNestedOption((path, fallback) => manager.get(path, fallback), String(key), defaultValue);
1403
1440
  resolveNestedOption = (read, key, defaultValue) => {
1404
1441
  const keys2 = key.split(".");
@@ -2007,10 +2044,76 @@ function outputIdentities(value) {
2007
2044
  visit(value);
2008
2045
  return Object.freeze(result2);
2009
2046
  }
2010
- var import_node_util3, import_mongoose3, import_express_json_router3, ServiceAuthorizationError, unsafeKeys;
2047
+ function tryOutputIdentitiesWithoutSnapshot(value) {
2048
+ const identities = [];
2049
+ const seen = /* @__PURE__ */ new WeakSet();
2050
+ const active = /* @__PURE__ */ new WeakSet();
2051
+ const fallback = {};
2052
+ let nodes = 0;
2053
+ function visit(input, depth) {
2054
+ if (++nodes > 2e4 || depth > 100) authorizationError("snapshot exceeds structural limits");
2055
+ if (typeof input === "function") authorizationError("functions are not policy values");
2056
+ if (typeof input === "symbol") authorizationError("symbols are not policy values");
2057
+ if (input === null || typeof input !== "object") return;
2058
+ if (import_node_util3.types.isProxy(input)) throw fallback;
2059
+ if (active.has(input)) authorizationError("cyclic input");
2060
+ if (!seen.has(input)) {
2061
+ seen.add(input);
2062
+ identities.push(input);
2063
+ }
2064
+ const prototype = Object.getPrototypeOf(input);
2065
+ if (import_node_util3.types.isDate(input)) {
2066
+ if (prototype === Date.prototype) return;
2067
+ throw fallback;
2068
+ }
2069
+ if (import_node_util3.types.isRegExp(input)) {
2070
+ if (prototype === RegExp.prototype) return;
2071
+ throw fallback;
2072
+ }
2073
+ if (import_node_util3.types.isUint8Array(input)) {
2074
+ if (prototype === import_node_buffer.Buffer.prototype) return;
2075
+ throw fallback;
2076
+ }
2077
+ if (import_node_util3.types.isMap(input) || import_node_util3.types.isSet(input)) throw fallback;
2078
+ const array = Array.isArray(input);
2079
+ if (!array) {
2080
+ if (prototype !== Object.prototype && prototype !== null) {
2081
+ let parent = prototype;
2082
+ for (let count = 0; parent && count < 100; count++) {
2083
+ if (import_node_util3.types.isProxy(parent)) throw fallback;
2084
+ if (parent === import_mongoose3.mongo.BSON.BSONValue.prototype) return;
2085
+ parent = Object.getPrototypeOf(parent);
2086
+ }
2087
+ throw fallback;
2088
+ }
2089
+ } else if (input.length > 2e4) authorizationError("snapshot array exceeds structural limits");
2090
+ active.add(input);
2091
+ try {
2092
+ for (const key of Reflect.ownKeys(input)) {
2093
+ if (array && key === "length") continue;
2094
+ if (typeof key !== "string" || unsafeKeys.has(key)) authorizationError("unsafe snapshot key");
2095
+ if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid array property");
2096
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
2097
+ if (!("value" in descriptor)) authorizationError("accessor/non-enumerable input");
2098
+ visit(descriptor.value, depth + 1);
2099
+ }
2100
+ } finally {
2101
+ active.delete(input);
2102
+ }
2103
+ }
2104
+ try {
2105
+ visit(value, 0);
2106
+ return Object.freeze(identities);
2107
+ } catch (error2) {
2108
+ if (error2 !== fallback) throw error2;
2109
+ return void 0;
2110
+ }
2111
+ }
2112
+ var import_node_util3, import_node_buffer, import_mongoose3, import_express_json_router3, ServiceAuthorizationError, unsafeKeys;
2011
2113
  var init_authorization_snapshot = __esm({
2012
2114
  "src/acl/authorization-snapshot.ts"() {
2013
2115
  import_node_util3 = require("util");
2116
+ import_node_buffer = require("buffer");
2014
2117
  import_mongoose3 = require("mongoose");
2015
2118
  import_express_json_router3 = __toESM(require("@web-ts-toolkit/express-json-router"));
2016
2119
  ServiceAuthorizationError = class extends import_express_json_router3.default.clientErrors.BadRequestError {
@@ -2047,6 +2150,9 @@ function isInputVirtualPath(catalog, path) {
2047
2150
  return false;
2048
2151
  }
2049
2152
  function matchesCatalogPattern(pattern, path, descendants = false) {
2153
+ if (typeof pattern === "string" && typeof path === "string" && !pattern.includes("$*")) {
2154
+ return pattern === path || !!descendants && path.startsWith(pattern) && path[pattern.length] === ".";
2155
+ }
2050
2156
  const expected = pattern.split(".");
2051
2157
  const actual = path.split(".");
2052
2158
  return (descendants ? actual.length >= expected.length : actual.length === expected.length) && expected.every((part, index) => part === "$*" || part === actual[index]);
@@ -2179,8 +2285,45 @@ var init_field_catalog = __esm({
2179
2285
  }
2180
2286
  });
2181
2287
 
2288
+ // src/runtime-context.ts
2289
+ function runWithRuntime(runtime, callback) {
2290
+ return runtimeStorage.run(runtime, callback);
2291
+ }
2292
+ function getActiveRuntime() {
2293
+ return runtimeStorage.getStore() ?? null;
2294
+ }
2295
+ var import_node_async_hooks2, runtimeStorage;
2296
+ var init_runtime_context = __esm({
2297
+ "src/runtime-context.ts"() {
2298
+ import_node_async_hooks2 = require("async_hooks");
2299
+ runtimeStorage = new import_node_async_hooks2.AsyncLocalStorage();
2300
+ }
2301
+ });
2302
+
2303
+ // src/meta.ts
2304
+ var getRuntime, getModelReference;
2305
+ var init_meta = __esm({
2306
+ "src/meta.ts"() {
2307
+ init_runtime();
2308
+ init_runtime_context();
2309
+ getRuntime = () => getActiveRuntime() ?? defaultRuntime;
2310
+ getModelReference = (modelName, refPath, runtime = getRuntime()) => {
2311
+ const instance = runtime.getModelInstance(modelName);
2312
+ let type = instance?.schema.path(refPath);
2313
+ const result2 = {};
2314
+ while (type) {
2315
+ result2.ref ??= type.options?.ref;
2316
+ result2.refPath ??= type.options?.refPath;
2317
+ if (type.instance !== "Array") break;
2318
+ type = type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
2319
+ }
2320
+ return result2;
2321
+ };
2322
+ }
2323
+ });
2324
+
2182
2325
  // src/acl/populate-target-configuration.ts
2183
- function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions) {
2326
+ function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions, defaults2 = runtime.getDefaultModelOptions()) {
2184
2327
  const label = `Populate target "${modelName}" for ${source}`;
2185
2328
  if (!proposedOptions && !runtime.hasModel(modelName))
2186
2329
  authorizationError(
@@ -2189,18 +2332,77 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
2189
2332
  const model = runtime.getModelInstance(modelName);
2190
2333
  if (!model) authorizationError(`${label} requires an actual registered Mongoose model in this runtime`);
2191
2334
  const options = proposedOptions ?? runtime.getModelOptions(modelName);
2192
- const permissionSchema = options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema;
2335
+ const permissionSchema = options.permissionSchema === void 0 ? defaults2.permissionSchema : options.permissionSchema;
2193
2336
  if (!(0, import_utils15.isPlainObject)(permissionSchema))
2194
2337
  authorizationError(
2195
2338
  `${label} requires an effective object permissionSchema; configure the model or runtime model defaults ({} explicitly closes business fields)`
2196
2339
  );
2197
2340
  return { model, options: { ...options, permissionSchema } };
2198
2341
  }
2342
+ function capturePopulateTargetBinding(runtime, sourceModelName, path) {
2343
+ const { ref, refPath } = getModelReference(sourceModelName, path, runtime);
2344
+ if (refPath !== void 0 || typeof ref === "function" && !("modelName" in ref))
2345
+ authorizationError(
2346
+ `Populate target for ${sourceModelName}.${path} requires a static string or Mongoose Model-valued source ref; dynamic refs/refPath cannot be bound before I/O`
2347
+ );
2348
+ const modelName = typeof ref === "string" ? ref : ref?.modelName;
2349
+ if (!modelName) return void 0;
2350
+ const target = capturePopulateTargetConfiguration(runtime, modelName, `${sourceModelName}.${path}`);
2351
+ const source = runtime.getModelInstance(sourceModelName);
2352
+ const actual = typeof ref === "string" ? source?.db.models[ref] : ref;
2353
+ if (!actual)
2354
+ authorizationError(
2355
+ `Populate target "${modelName}" for ${sourceModelName}.${path} is missing on the source connection; configure the actual model bound to the source ref in this runtime`
2356
+ );
2357
+ if (actual !== target.model)
2358
+ authorizationError(
2359
+ `Populate target "${modelName}" for ${sourceModelName}.${path} resolves to a different actual Mongoose model than this runtime configured; register and configure the actual source ref instance`
2360
+ );
2361
+ return { ...target, modelName };
2362
+ }
2199
2363
  var import_utils15;
2200
2364
  var init_populate_target_configuration = __esm({
2201
2365
  "src/acl/populate-target-configuration.ts"() {
2202
2366
  import_utils15 = require("@web-ts-toolkit/utils");
2203
2367
  init_authorization_snapshot();
2368
+ init_meta();
2369
+ }
2370
+ });
2371
+
2372
+ // src/acl/populate-policy.ts
2373
+ function capturePopulatePolicyDefaults(runtime) {
2374
+ const options = runtime.getDefaultModelOptions();
2375
+ const token = () => {
2376
+ };
2377
+ defaults.set(
2378
+ token,
2379
+ Object.freeze({
2380
+ requireOperationAccessForPopulateQueries: options.requireOperationAccessForPopulateQueries !== false,
2381
+ requireOperationAccessForPopulateDependencies: options.requireOperationAccessForPopulateDependencies !== false
2382
+ })
2383
+ );
2384
+ return token;
2385
+ }
2386
+ function resolvePopulatePolicy(options, token) {
2387
+ const captured = defaults.get(token);
2388
+ if (!captured) return authorizationError("invalid captured populate model defaults");
2389
+ const resolve = (key) => (options[key] === void 0 ? captured[key] : options[key]) !== false;
2390
+ return Object.freeze({
2391
+ requireOperationAccessForPopulateQueries: resolve(populatePolicyKeys[0]),
2392
+ requireOperationAccessForPopulateDependencies: resolve(populatePolicyKeys[1])
2393
+ });
2394
+ }
2395
+ function getCapturedPopulatePolicyDefaults(configuration) {
2396
+ const token = configuration.populatePolicyDefaults;
2397
+ if (!token || !defaults.has(token)) return authorizationError("missing captured populate model defaults");
2398
+ return token;
2399
+ }
2400
+ var defaults;
2401
+ var init_populate_policy2 = __esm({
2402
+ "src/acl/populate-policy.ts"() {
2403
+ init_populate_policy();
2404
+ init_authorization_snapshot();
2405
+ defaults = /* @__PURE__ */ new WeakMap();
2204
2406
  }
2205
2407
  });
2206
2408
 
@@ -2294,9 +2496,7 @@ function normalizeSelection(select, catalog, label) {
2294
2496
  includeId: selection.includes("_id")
2295
2497
  };
2296
2498
  }
2297
- function captureVirtualPopulateDependencies(runtime, modelName, options, globalOptions = runtime.getGlobalOptions()) {
2298
- const requireOperationAccessForPopulateDependencies = globalOptions.requireOperationAccessForPopulateDependencies !== false;
2299
- const requireOperationAccessForPopulateQueries = globalOptions.requireOperationAccessForPopulateQueries !== false;
2499
+ function captureVirtualPopulateDependencies(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime), proposed) {
2300
2500
  const model = runtime.getModelInstance(modelName);
2301
2501
  const targets = /* @__PURE__ */ new Map();
2302
2502
  const scopes = [];
@@ -2340,18 +2540,19 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, globalO
2340
2540
  runtime,
2341
2541
  ref,
2342
2542
  `dependsOnPopulate virtual "${label}"`,
2343
- ref === modelName ? options : void 0
2543
+ ref === modelName ? options : proposed?.models.get(ref),
2544
+ proposed?.defaults
2344
2545
  );
2345
- const defaults = runtime.getDefaultModelOptions();
2346
- const readOption = (key) => resolveNestedOption((path2, fallback) => (0, import_utils16.get)(targetOptions, path2, fallback), key, (0, import_utils16.get)(defaults, key));
2347
- const documentPermissionField = targetOptions.documentPermissionField ?? defaults.documentPermissionField;
2546
+ const defaults2 = proposed?.defaults ?? runtime.getDefaultModelOptions();
2547
+ const readOption = (key) => resolveNestedOption((path2, fallback) => (0, import_utils16.get)(targetOptions, path2, fallback), key, (0, import_utils16.get)(defaults2, key));
2548
+ const documentPermissionField = targetOptions.documentPermissionField ?? defaults2.documentPermissionField;
2348
2549
  const catalog = captureAuthorizationFieldCatalog(targetModel.schema, void 0, documentPermissionField);
2349
2550
  const configuration = copyAuthorizationValue(
2350
2551
  {
2351
2552
  catalog,
2352
2553
  documentPermissionField,
2353
- requireOperationAccessForPopulateDependencies,
2354
- requireOperationAccessForPopulateQueries,
2554
+ populatePolicyDefaults,
2555
+ ...resolvePopulatePolicy(targetOptions, populatePolicyDefaults),
2355
2556
  permissionSchema: targetOptions.permissionSchema,
2356
2557
  operationAccess: { read: readOption("operationAccess.read") },
2357
2558
  baseFilter: { read: readOption("baseFilter.read") },
@@ -2432,8 +2633,8 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, globalO
2432
2633
  visit(options.virtuals ?? {}, model?.schema, "", [], !!model && varyingModel(model));
2433
2634
  return Object.freeze({ scopes: Object.freeze(scopes) });
2434
2635
  }
2435
- function captureVirtualPopulateSnapshot(runtime, modelName, options, globalOptions = runtime.getGlobalOptions()) {
2436
- const snapshot = captureVirtualPopulateDependencies(runtime, modelName, options, globalOptions);
2636
+ function captureVirtualPopulateSnapshot(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime)) {
2637
+ const snapshot = captureVirtualPopulateDependencies(runtime, modelName, options, populatePolicyDefaults);
2437
2638
  const token = () => {
2438
2639
  };
2439
2640
  snapshots.set(token, snapshot);
@@ -2467,6 +2668,7 @@ var init_virtual_populate_dependencies = __esm({
2467
2668
  init_field_catalog();
2468
2669
  init_virtual_descriptor();
2469
2670
  init_populate_target_configuration();
2671
+ init_populate_policy2();
2470
2672
  elementType = (type) => type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
2471
2673
  join = (prefix, path) => prefix ? `${prefix}.${path}` : path;
2472
2674
  within = (path, parent) => path === parent || path.startsWith(`${parent}.`);
@@ -2481,12 +2683,13 @@ var init_virtual_populate_dependencies = __esm({
2481
2683
  });
2482
2684
 
2483
2685
  // src/runtime.ts
2484
- var import_mongoose4, import_mongoose_schema_jsonschema, import_utils17, mongooseJsonSchemaInitialized, ensureMongooseJsonSchemaInitialized, pluralize, FIELD_ACCESS_KEYS, defaultModelOptions, defaultDataOptions, normalizeBasePath, hasModelPermission, classifyPermissionSchema, refreshPermissionMetadata, VIRTUAL_SUPPORTED_ACCESSES, VIRTUAL_UNSUPPORTED_ACCESSES, VIRTUAL_RESERVED_NAMES, VIRTUAL_DANGEROUS_SEGMENTS, VIRTUAL_NAME_PATTERN, isVirtualContainerValue2, virtualFullPath, virtualPathsOverlap, collectStoredTopLevel, getChildSchemaForField, getNestedChildFields, cloneVirtualsForValidation, validateVirtualDependsOn, validateVirtualLeafValue, validateVirtualsScope, validateVirtualsTree, AccessRuntime, defaultRuntime;
2686
+ var import_mongoose4, import_mongoose_schema_jsonschema, import_utils17, mongooseJsonSchemaInitialized, ensureMongooseJsonSchemaInitialized, pluralize, FIELD_ACCESS_KEYS, defaultModelOptions, modelOverrides, defaultDataOptions, normalizeBasePath, hasModelPermission, classifyPermissionSchema, refreshPermissionMetadata, VIRTUAL_SUPPORTED_ACCESSES, VIRTUAL_UNSUPPORTED_ACCESSES, VIRTUAL_RESERVED_NAMES, VIRTUAL_DANGEROUS_SEGMENTS, VIRTUAL_NAME_PATTERN, isVirtualContainerValue2, virtualFullPath, virtualPathsOverlap, collectStoredTopLevel, getChildSchemaForField, getNestedChildFields, cloneModelOptionForUpdate, validateVirtualDependsOn, validateVirtualLeafValue, validateVirtualsScope, validateVirtualsTree, AccessRuntime, defaultRuntime;
2485
2687
  var init_runtime = __esm({
2486
2688
  "src/runtime.ts"() {
2487
2689
  import_mongoose4 = __toESM(require("mongoose"));
2488
2690
  init_public_admission();
2489
2691
  init_hydration();
2692
+ init_populate_policy();
2490
2693
  import_mongoose_schema_jsonschema = __toESM(require("mongoose-schema-jsonschema"));
2491
2694
  import_utils17 = require("@web-ts-toolkit/utils");
2492
2695
  init_helpers();
@@ -2498,6 +2701,7 @@ var init_runtime = __esm({
2498
2701
  init_request_complexity();
2499
2702
  init_virtual_descriptor();
2500
2703
  init_virtual_populate_dependencies();
2704
+ init_unsafe_snapshot_options();
2501
2705
  mongooseJsonSchemaInitialized = false;
2502
2706
  ensureMongooseJsonSchemaInitialized = () => {
2503
2707
  if (mongooseJsonSchemaInitialized) return;
@@ -2510,6 +2714,15 @@ var init_runtime = __esm({
2510
2714
  basePath: null,
2511
2715
  alwaysSelectFields: []
2512
2716
  };
2717
+ modelOverrides = (options) => {
2718
+ const result2 = Object.fromEntries(
2719
+ Object.entries(options).filter(
2720
+ ([key, value]) => value !== void 0 || key === "operationAccess" || isPopulatePolicyKey(key)
2721
+ )
2722
+ );
2723
+ for (const key of unsafeSnapshotOptions) if (key in result2) result2[key] = result2[key] === true;
2724
+ return cloneOptionsSnapshot(result2);
2725
+ };
2513
2726
  defaultDataOptions = {
2514
2727
  basePath: null,
2515
2728
  parentPath: "/",
@@ -2643,12 +2856,12 @@ var init_runtime = __esm({
2643
2856
  }
2644
2857
  return fields;
2645
2858
  };
2646
- cloneVirtualsForValidation = (value) => {
2647
- if (Array.isArray(value)) return value.map((item) => cloneVirtualsForValidation(item));
2859
+ cloneModelOptionForUpdate = (value) => {
2860
+ if (Array.isArray(value)) return value.map((item) => cloneModelOptionForUpdate(item));
2648
2861
  if (!value || typeof value !== "object") return value;
2649
2862
  if (Object.getPrototypeOf(value) !== Object.prototype) return value;
2650
2863
  return Object.fromEntries(
2651
- Object.entries(value).map(([k, v]) => [k, cloneVirtualsForValidation(v)])
2864
+ Object.entries(value).map(([k, v]) => [k, cloneModelOptionForUpdate(v)])
2652
2865
  );
2653
2866
  };
2654
2867
  validateVirtualDependsOn = (dependsOn, entryLabel, storedFields, siblingVirtualNames) => {
@@ -2844,8 +3057,6 @@ var init_runtime = __esm({
2844
3057
  {
2845
3058
  requestPermissionField: "_permissions",
2846
3059
  globalPermissions: () => ({}),
2847
- requireOperationAccessForPopulateQueries: true,
2848
- requireOperationAccessForPopulateDependencies: true,
2849
3060
  logger: defaultLogger,
2850
3061
  requestComplexity: defaultRequestComplexity
2851
3062
  },
@@ -2860,15 +3071,20 @@ var init_runtime = __esm({
2860
3071
  queryRouteSegment: "__query",
2861
3072
  mutationRouteSegment: "__mutation",
2862
3073
  operationAccess: false,
3074
+ requireOperationAccessForPopulateQueries: true,
3075
+ requireOperationAccessForPopulateDependencies: true,
2863
3076
  modelPermissionPrefix: "",
2864
3077
  unsafeSkipListDocumentSnapshotChecks: false,
2865
3078
  unsafeSkipReadDocumentSnapshotChecks: false,
2866
3079
  unsafeSkipListOutputSnapshotChecks: false,
2867
3080
  unsafeSkipReadOutputSnapshotChecks: false,
2868
3081
  unsafeSkipListNestedDocumentSnapshotChecks: false,
2869
- unsafeSkipReadNestedDocumentSnapshotChecks: false
3082
+ unsafeSkipReadNestedDocumentSnapshotChecks: false,
3083
+ unsafeSkipListInitialOutputSnapshotCopy: false,
3084
+ unsafeSkipReadInitialOutputSnapshotCopy: false
2870
3085
  }).build();
2871
3086
  this.modelOptions = {};
3087
+ this.modelOptionOverrides = {};
2872
3088
  this.modelJsonSchemas = {};
2873
3089
  this.dataOptions = {};
2874
3090
  this.modelRefs = {};
@@ -2956,6 +3172,7 @@ var init_runtime = __esm({
2956
3172
  globalOptions: this.globalOptions.snapshot(),
2957
3173
  defaultModelOptions: this.defaultModelOptions.snapshot(),
2958
3174
  modelOptions: modelOptionsSnap,
3175
+ modelOptionOverrides: { ...this.modelOptionOverrides },
2959
3176
  dataOptions: dataOptionsSnap,
2960
3177
  modelInstances: { ...this.modelInstances },
2961
3178
  modelJsonSchemas: { ...this.modelJsonSchemas },
@@ -2970,6 +3187,10 @@ var init_runtime = __esm({
2970
3187
  restoreBootstrapSnapshot(snapshot) {
2971
3188
  this.globalOptions.restore(snapshot.globalOptions);
2972
3189
  this.defaultModelOptions.restore(snapshot.defaultModelOptions);
3190
+ for (const name of Object.keys(this.modelOptionOverrides)) delete this.modelOptionOverrides[name];
3191
+ for (const [name, options] of Object.entries(snapshot.modelOptionOverrides)) {
3192
+ this.modelOptionOverrides[name] = modelOverrides(options);
3193
+ }
2973
3194
  for (const name of Object.keys(this.modelOptions)) {
2974
3195
  if (!(name in snapshot.modelOptions)) {
2975
3196
  delete this.modelOptions[name];
@@ -2980,8 +3201,7 @@ var init_runtime = __esm({
2980
3201
  if (existing) {
2981
3202
  existing.restore(opts);
2982
3203
  } else {
2983
- const mgr = this.createModelOptions(name);
2984
- mgr.restore(opts);
3204
+ const mgr = this.createModelOptions(name, opts);
2985
3205
  this.modelOptions[name] = mgr;
2986
3206
  }
2987
3207
  }
@@ -3024,18 +3244,11 @@ var init_runtime = __esm({
3024
3244
  }
3025
3245
  /** Shallowly replace supplied global values; nested objects such as requestComplexity are not deep-merged. */
3026
3246
  setGlobalOptions(options) {
3027
- const next = { ...options };
3028
- if ("requireOperationAccessForPopulateQueries" in next)
3029
- next.requireOperationAccessForPopulateQueries = next.requireOperationAccessForPopulateQueries !== false;
3030
- if ("requireOperationAccessForPopulateDependencies" in next)
3031
- next.requireOperationAccessForPopulateDependencies = next.requireOperationAccessForPopulateDependencies !== false;
3032
- this.globalOptions.assign(next);
3247
+ for (const key of populatePolicyKeys) if (key in options) assertNoGlobalPopulatePolicy(key);
3248
+ this.globalOptions.assign({ ...options });
3033
3249
  }
3034
3250
  setGlobalOption(key, value) {
3035
- if (key === "requireOperationAccessForPopulateQueries" || key === "requireOperationAccessForPopulateDependencies") {
3036
- this.globalOptions.set(key, value !== false);
3037
- return;
3038
- }
3251
+ assertNoGlobalPopulatePolicy(String(key));
3039
3252
  this.globalOptions.set(key, value);
3040
3253
  }
3041
3254
  getGlobalOptions() {
@@ -3044,28 +3257,30 @@ var init_runtime = __esm({
3044
3257
  getGlobalOption(key, defaultValue) {
3045
3258
  return this.globalOptions.get(key, defaultValue);
3046
3259
  }
3047
- /** Update model starting defaults shallowly; already-stored model values are not broadcast-replaced. */
3260
+ /** Update inherited model defaults shallowly. Explicit model values and captured calls are unchanged. */
3048
3261
  setDefaultModelOptions(options) {
3049
3262
  assertPublicDefaults(options.defaults);
3050
3263
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
3051
- this.defaultModelOptions.assign(options);
3264
+ const draft = new OptionsManager(
3265
+ this.getDefaultModelOptions()
3266
+ ).build();
3267
+ draft.assign(normalizePopulatePolicyOptions(options));
3268
+ this.publishDefaultModelOptions(draft.fetch());
3052
3269
  }
3053
3270
  setDefaultModelOption(key, value) {
3054
3271
  const keyStr = String(key);
3055
- if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
3056
- this.defaultModelOptions.set(
3057
- "hydration",
3058
- normalizeHydrationUpdate(this.getDefaultModelOptions().hydration, keyStr, value)
3059
- );
3060
- return;
3061
- }
3062
- if (keyStr === "defaults") assertPublicDefaults(value);
3063
- else if (keyStr.startsWith("defaults.")) {
3064
- const proposed = {};
3065
- (0, import_utils17.set)(proposed, keyStr.slice("defaults.".length), value);
3066
- assertPublicDefaults(proposed);
3272
+ const draft = new OptionsManager(
3273
+ this.getDefaultModelOptions()
3274
+ ).build();
3275
+ if (isPopulatePolicyKey(keyStr)) {
3276
+ draft.set(keyStr, normalizePopulatePolicyValue(value));
3277
+ } else if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
3278
+ draft.set("hydration", normalizeHydrationUpdate(this.getDefaultModelOptions().hydration, keyStr, value));
3279
+ } else {
3280
+ draft.set(key, value);
3067
3281
  }
3068
- this.defaultModelOptions.set(key, value);
3282
+ assertPublicDefaults(draft.fetch().defaults);
3283
+ this.publishDefaultModelOptions(draft.fetch());
3069
3284
  }
3070
3285
  getDefaultModelOptions() {
3071
3286
  return this.defaultModelOptions.fetch();
@@ -3073,30 +3288,103 @@ var init_runtime = __esm({
3073
3288
  getDefaultModelOption(key, defaultValue) {
3074
3289
  return this.defaultModelOptions.get(key, defaultValue);
3075
3290
  }
3076
- createModelOptions(modelName) {
3291
+ resolveModelOptions(modelName, overrides = this.modelOptionOverrides[modelName] ?? {}, defaults2 = this.getDefaultModelOptions()) {
3292
+ const inherited = { ...defaults2 };
3293
+ for (const key of populatePolicyKeys) delete inherited[key];
3294
+ const effective = { ...defaultModelOptions, ...inherited, ...overrides, modelName };
3295
+ effective.basePath = normalizeBasePath(modelName, effective.basePath);
3296
+ for (const key of unsafeSnapshotOptions) effective[key] = effective[key] === true;
3297
+ refreshPermissionMetadata(effective);
3298
+ return cloneOptionsSnapshot(effective);
3299
+ }
3300
+ validateModelOptions(modelName, options, proposed) {
3301
+ validateVirtualsTree(
3302
+ this.getModelInstance(modelName),
3303
+ options.virtuals,
3304
+ options.documentPermissionField ?? "_permissions",
3305
+ modelName
3306
+ );
3307
+ captureVirtualPopulateDependencies(this, modelName, options, void 0, proposed);
3308
+ }
3309
+ publishDefaultModelOptions(options) {
3310
+ const next = { ...options };
3311
+ for (const key of unsafeSnapshotOptions) if (key in next) next[key] = next[key] === true;
3312
+ const defaults2 = cloneOptionsSnapshot(next);
3313
+ const models = new Map(
3314
+ Object.keys(this.modelOptions).map((name) => [name, this.resolveModelOptions(name, void 0, defaults2)])
3315
+ );
3316
+ for (const [name, options2] of models) this.validateModelOptions(name, options2, { defaults: defaults2, models });
3317
+ this.deferSnapshotWarnings(() => {
3318
+ this.defaultModelOptions.restore(defaults2);
3319
+ for (const [name, options2] of models) this.modelOptions[name].restore(options2);
3320
+ });
3321
+ }
3322
+ warnSnapshotFlag(modelName, key) {
3323
+ if (this.pendingSnapshotWarnings) {
3324
+ this.pendingSnapshotWarnings.push({ modelName, key });
3325
+ return;
3326
+ }
3327
+ const operation = key.startsWith("unsafeSkipRead") ? "read" : "list";
3328
+ const category = key.includes("NestedDocument") ? "nested-document" : key.includes("Output") ? "output" : "document";
3329
+ const risk = category === "output" ? "output mutation" : "source mutation";
3330
+ try {
3331
+ this.getGlobalOption("logger")?.warn?.(
3332
+ `UNSAFE: ${operation} ${category} snapshot checks disabled; ${risk} can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
3333
+ { modelName }
3334
+ );
3335
+ } catch {
3336
+ }
3337
+ }
3338
+ deferSnapshotWarnings(publish) {
3339
+ if (this.pendingSnapshotWarnings) return publish();
3340
+ const copyModes = this.initialOutputCopyModes();
3341
+ const pending = [];
3342
+ this.pendingSnapshotWarnings = pending;
3343
+ let result2;
3344
+ try {
3345
+ result2 = publish();
3346
+ } finally {
3347
+ this.pendingSnapshotWarnings = void 0;
3348
+ }
3349
+ const nextCopyModes = this.initialOutputCopyModes();
3350
+ for (const { modelName, key } of pending) this.warnSnapshotFlag(modelName, key);
3351
+ for (const [modelName, modes] of nextCopyModes) {
3352
+ for (const operation of ["List", "Read"]) {
3353
+ const mode = modes[operation];
3354
+ if (mode === "off" || mode === copyModes.get(modelName)?.[operation]) continue;
3355
+ const key = `unsafeSkip${operation}InitialOutputSnapshotCopy`;
3356
+ const prerequisite = `unsafeSkip${operation}OutputSnapshotChecks`;
3357
+ try {
3358
+ this.getGlobalOption("logger")?.warn?.(
3359
+ mode === "active" ? `UNSAFE: ${operation.toLowerCase()} initial output snapshot copying disabled for eligible graphs; omitted native normalization/validation can change side effects and authorization outcomes. Restore ${key}=false after the temporary workaround.` : `UNSAFE: ${key} is dormant; requires ${prerequisite}=true. Initial copying and output comparisons remain enabled. Restore ${key}=false if not intended.`,
3360
+ { modelName }
3361
+ );
3362
+ } catch {
3363
+ }
3364
+ }
3365
+ }
3366
+ return result2;
3367
+ }
3368
+ initialOutputCopyModes() {
3369
+ return new Map(
3370
+ Object.entries(this.modelOptions).map(([modelName, options]) => {
3371
+ const mode = (operation) => options.get(`unsafeSkip${operation}InitialOutputSnapshotCopy`) !== true ? "off" : options.get(`unsafeSkip${operation}OutputSnapshotChecks`) === true ? "active" : "dormant";
3372
+ return [modelName, { List: mode("List"), Read: mode("Read") }];
3373
+ })
3374
+ );
3375
+ }
3376
+ createModelOptions(modelName, options = this.resolveModelOptions(modelName)) {
3077
3377
  const model = this.getModelInstance(modelName);
3078
3378
  if (!model) {
3079
3379
  throw new Error(
3080
3380
  `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this isolated runtime.`
3081
3381
  );
3082
3382
  }
3083
- const manager = new OptionsManager({
3084
- ...defaultModelOptions,
3085
- modelName
3086
- });
3383
+ const manager = new OptionsManager(options);
3087
3384
  const snapshotFlagChanged = (newValue, key, target, oldValue) => {
3088
3385
  target[key] = newValue === true;
3089
3386
  if (newValue !== true || oldValue === true) return;
3090
- const operation = key.startsWith("unsafeSkipRead") ? "read" : "list";
3091
- const category = key.includes("NestedDocument") ? "nested-document" : key.includes("Output") ? "output" : "document";
3092
- const risk = category === "output" ? "output mutation" : "source mutation";
3093
- try {
3094
- this.getGlobalOption("logger")?.warn?.(
3095
- `UNSAFE: ${operation} ${category} snapshot checks disabled; ${risk} can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
3096
- { modelName }
3097
- );
3098
- } catch {
3099
- }
3387
+ this.warnSnapshotFlag(modelName, key);
3100
3388
  };
3101
3389
  manager.onchange("permissionSchema", function(_newval, _key, target) {
3102
3390
  refreshPermissionMetadata(target);
@@ -3114,13 +3402,17 @@ var init_runtime = __esm({
3114
3402
  getOrCreateModelOptions(modelName) {
3115
3403
  let manager = this.modelOptions[modelName];
3116
3404
  if (!manager) {
3117
- manager = this.createModelOptions(modelName);
3118
- this.modelOptions[modelName] = manager;
3405
+ manager = this.deferSnapshotWarnings(() => {
3406
+ const created = this.createModelOptions(modelName);
3407
+ this.modelOptions[modelName] = created;
3408
+ return created;
3409
+ });
3119
3410
  }
3120
3411
  return manager;
3121
3412
  }
3122
3413
  /**
3123
- * Assign `{ ...modelDefaults, ...storedOptions, ...options }` shallowly. A supplied
3414
+ * Update explicit model overrides shallowly; undefined restores default inheritance
3415
+ * (operationAccess preserves its existing exact-key-only default fallback). A supplied
3124
3416
  * operationAccess/defaults object replaces that whole value. Defaults accept only
3125
3417
  * query/presentation settings; virtual configuration is validated before assignment.
3126
3418
  * Existing router.options remains its construction-time snapshot. Fresh model-service
@@ -3128,22 +3420,23 @@ var init_runtime = __esm({
3128
3420
  */
3129
3421
  setModelOptions(modelName, options) {
3130
3422
  assertPublicDefaults(options.defaults);
3423
+ options = normalizePopulatePolicyOptions(options);
3131
3424
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
3132
- const defaultOptions = this.getDefaultModelOptions();
3133
- const currentModelOptions = this.modelOptions[modelName]?.fetch() ?? { ...defaultModelOptions, modelName };
3134
- const merged = { ...defaultOptions, ...currentModelOptions, ...options };
3135
- const model = this.getModelInstance(modelName);
3136
- const permissionField = merged.documentPermissionField ?? currentModelOptions.documentPermissionField ?? this.getDefaultModelOption("documentPermissionField") ?? "_permissions";
3137
- validateVirtualsTree(model, merged.virtuals, permissionField, modelName);
3138
- captureVirtualPopulateDependencies(this, modelName, merged);
3139
- const manager = this.getOrCreateModelOptions(modelName);
3140
- manager.assign({ ...defaultOptions, ...currentModelOptions, ...options });
3425
+ const overrides = modelOverrides({ ...this.modelOptionOverrides[modelName], ...options });
3426
+ const effective = this.resolveModelOptions(modelName, overrides);
3427
+ this.validateModelOptions(modelName, effective);
3428
+ this.deferSnapshotWarnings(() => {
3429
+ const manager = this.modelOptions[modelName];
3430
+ if (manager) manager.restore(effective);
3431
+ else this.modelOptions[modelName] = this.createModelOptions(modelName, effective);
3432
+ this.modelOptionOverrides[modelName] = overrides;
3433
+ });
3141
3434
  }
3142
3435
  setModelOption(modelName, key, value) {
3143
3436
  const keyStr = String(key);
3144
3437
  if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
3145
- const hydration = normalizeHydrationUpdate(this.modelOptions[modelName]?.get("hydration"), keyStr, value);
3146
- this.getOrCreateModelOptions(modelName).set("hydration", hydration);
3438
+ const hydration = normalizeHydrationUpdate(this.resolveModelOptions(modelName).hydration, keyStr, value);
3439
+ this.setModelOptions(modelName, { hydration });
3147
3440
  return;
3148
3441
  }
3149
3442
  if (keyStr === "defaults") assertPublicDefaults(value);
@@ -3152,47 +3445,20 @@ var init_runtime = __esm({
3152
3445
  (0, import_utils17.set)(proposed, keyStr.slice("defaults.".length), value);
3153
3446
  assertPublicDefaults(proposed);
3154
3447
  }
3155
- const manager = this.modelOptions[modelName];
3156
- if (keyStr === "virtuals" || keyStr.startsWith("virtuals.") || keyStr === "documentPermissionField") {
3157
- const model = this.getModelInstance(modelName);
3158
- const currentVirtuals = manager?.get("virtuals");
3159
- const currentPermissionField = manager?.get("documentPermissionField") ?? this.getDefaultModelOption("documentPermissionField") ?? "_permissions";
3160
- let proposedVirtuals = currentVirtuals;
3161
- let proposedPermissionField = currentPermissionField;
3162
- if (keyStr === "documentPermissionField") {
3163
- proposedPermissionField = value;
3164
- } else if (keyStr === "virtuals") {
3165
- proposedVirtuals = value;
3166
- } else {
3167
- const cloned = cloneVirtualsForValidation(currentVirtuals ?? {});
3168
- const nestedPath = keyStr.slice("virtuals.".length);
3169
- if (value === void 0) {
3170
- const segments = nestedPath.split(".");
3171
- let cursor = cloned;
3172
- for (let i = 0; i < segments.length - 1; i++) {
3173
- if (!(0, import_utils17.isPlainObject)(cursor)) break;
3174
- cursor = cursor[segments[i]];
3175
- }
3176
- if ((0, import_utils17.isPlainObject)(cursor)) {
3177
- delete cursor[segments[segments.length - 1]];
3178
- }
3179
- proposedVirtuals = cloned;
3180
- } else {
3181
- (0, import_utils17.set)(cloned, nestedPath, value);
3182
- proposedVirtuals = cloned;
3183
- }
3184
- }
3185
- validateVirtualsTree(model, proposedVirtuals, proposedPermissionField, modelName);
3186
- captureVirtualPopulateDependencies(this, modelName, {
3187
- ...this.getDefaultModelOptions(),
3188
- ...manager?.fetch(),
3189
- virtuals: proposedVirtuals,
3190
- documentPermissionField: proposedPermissionField
3191
- });
3448
+ const [root, ...path] = keyStr.split(".");
3449
+ if (!path.length) {
3450
+ this.setModelOptions(modelName, { [root]: value });
3451
+ return;
3192
3452
  }
3193
- this.getOrCreateModelOptions(modelName).set(key, value);
3194
- }
3195
- /** Frozen stored snapshot, not fully resolved per-path defaults. Read again for current configuration. */
3453
+ const current = this.resolveModelOptions(modelName);
3454
+ const nested = cloneModelOptionForUpdate((0, import_utils17.isPlainObject)(current[root]) ? current[root] : {});
3455
+ if (root === "virtuals" && value === void 0) {
3456
+ const parent = path.length === 1 ? nested : (0, import_utils17.get)(nested, path.slice(0, -1));
3457
+ if ((0, import_utils17.isPlainObject)(parent)) delete parent[path[path.length - 1]];
3458
+ } else (0, import_utils17.set)(nested, path, value);
3459
+ this.setModelOptions(modelName, { [root]: nested });
3460
+ }
3461
+ /** Frozen model/default snapshot; populate flags remain raw overrides. Read again for current values. */
3196
3462
  getModelOptions(modelName) {
3197
3463
  const manager = this.getOrCreateModelOptions(modelName);
3198
3464
  return manager.fetch();
@@ -3359,132 +3625,117 @@ var init_runtime = __esm({
3359
3625
  }
3360
3626
  });
3361
3627
 
3362
- // src/runtime-context.ts
3363
- function runWithRuntime(runtime, callback) {
3364
- return runtimeStorage.run(runtime, callback);
3365
- }
3366
- function getActiveRuntime() {
3367
- return runtimeStorage.getStore() ?? null;
3368
- }
3369
- var import_node_async_hooks2, runtimeStorage;
3370
- var init_runtime_context = __esm({
3371
- "src/runtime-context.ts"() {
3372
- import_node_async_hooks2 = require("async_hooks");
3373
- runtimeStorage = new import_node_async_hooks2.AsyncLocalStorage();
3374
- }
3375
- });
3376
-
3377
3628
  // src/options/global-options.ts
3378
- var getRuntime, setGlobalOptions, setGlobalOption, getGlobalOptions, getGlobalOption;
3629
+ var getRuntime2, setGlobalOptions, setGlobalOption, getGlobalOptions, getGlobalOption;
3379
3630
  var init_global_options = __esm({
3380
3631
  "src/options/global-options.ts"() {
3381
3632
  init_runtime();
3382
3633
  init_runtime_context();
3383
- getRuntime = () => getActiveRuntime() ?? defaultRuntime;
3634
+ getRuntime2 = () => getActiveRuntime() ?? defaultRuntime;
3384
3635
  setGlobalOptions = (options) => {
3385
- getRuntime().setGlobalOptions(options);
3636
+ getRuntime2().setGlobalOptions(options);
3386
3637
  };
3387
3638
  setGlobalOption = (key, value) => {
3388
- getRuntime().setGlobalOption(key, value);
3639
+ getRuntime2().setGlobalOption(key, value);
3389
3640
  };
3390
3641
  getGlobalOptions = () => {
3391
- return getRuntime().getGlobalOptions();
3642
+ return getRuntime2().getGlobalOptions();
3392
3643
  };
3393
3644
  getGlobalOption = (key, defaultValue) => {
3394
- return getRuntime().getGlobalOption(key, defaultValue);
3645
+ return getRuntime2().getGlobalOption(key, defaultValue);
3395
3646
  };
3396
3647
  }
3397
3648
  });
3398
3649
 
3399
3650
  // src/options/model-options.ts
3400
- var getRuntime2, setModelOptions, setModelOption, getModelOptions, getModelOption, getExactModelOption, getModelNames, getModelJsonSchema, registerModelInstance, hasModelInstance, getModelInstance;
3651
+ var getRuntime3, setModelOptions, setModelOption, getModelOptions, getModelOption, getExactModelOption, getModelNames, getModelJsonSchema, registerModelInstance, hasModelInstance, getModelInstance;
3401
3652
  var init_model_options = __esm({
3402
3653
  "src/options/model-options.ts"() {
3403
3654
  init_runtime();
3404
3655
  init_runtime_context();
3405
- getRuntime2 = () => getActiveRuntime() ?? defaultRuntime;
3656
+ getRuntime3 = () => getActiveRuntime() ?? defaultRuntime;
3406
3657
  setModelOptions = (modelName, options) => {
3407
- getRuntime2().setModelOptions(modelName, options);
3658
+ getRuntime3().setModelOptions(modelName, options);
3408
3659
  };
3409
3660
  setModelOption = (modelName, key, value) => {
3410
- getRuntime2().setModelOption(modelName, key, value);
3661
+ getRuntime3().setModelOption(modelName, key, value);
3411
3662
  };
3412
3663
  getModelOptions = (modelName) => {
3413
- return getRuntime2().getModelOptions(modelName);
3664
+ return getRuntime3().getModelOptions(modelName);
3414
3665
  };
3415
3666
  getModelOption = (modelName, key, defaultValue) => {
3416
- return getRuntime2().getModelOption(modelName, key, defaultValue);
3667
+ return getRuntime3().getModelOption(modelName, key, defaultValue);
3417
3668
  };
3418
3669
  getExactModelOption = (modelName, key) => {
3419
- return getRuntime2().getExactModelOption(modelName, key);
3670
+ return getRuntime3().getExactModelOption(modelName, key);
3420
3671
  };
3421
3672
  getModelNames = () => {
3422
3673
  return (getActiveRuntime() ?? defaultRuntime).getModelNames();
3423
3674
  };
3424
3675
  getModelJsonSchema = (modelName) => {
3425
- return getRuntime2().getModelJsonSchema(modelName);
3676
+ return getRuntime3().getModelJsonSchema(modelName);
3426
3677
  };
3427
3678
  registerModelInstance = (modelName, model) => {
3428
- getRuntime2().registerModelInstance(modelName, model);
3679
+ getRuntime3().registerModelInstance(modelName, model);
3429
3680
  };
3430
3681
  hasModelInstance = (modelName) => {
3431
- return getRuntime2().hasModelInstance(modelName);
3682
+ return getRuntime3().hasModelInstance(modelName);
3432
3683
  };
3433
3684
  getModelInstance = (modelName) => {
3434
- return getRuntime2().getModelInstance(modelName);
3685
+ return getRuntime3().getModelInstance(modelName);
3435
3686
  };
3436
3687
  }
3437
3688
  });
3438
3689
 
3439
3690
  // src/options/default-model-options.ts
3440
- var getRuntime3, setDefaultModelOptions, setDefaultModelOption, getDefaultModelOptions, getDefaultModelOption;
3691
+ var getRuntime4, setDefaultModelOptions, setDefaultModelOption, getDefaultModelOptions, getDefaultModelOption;
3441
3692
  var init_default_model_options = __esm({
3442
3693
  "src/options/default-model-options.ts"() {
3443
3694
  init_runtime();
3444
3695
  init_runtime_context();
3445
- getRuntime3 = () => getActiveRuntime() ?? defaultRuntime;
3696
+ getRuntime4 = () => getActiveRuntime() ?? defaultRuntime;
3446
3697
  setDefaultModelOptions = (options) => {
3447
- getRuntime3().setDefaultModelOptions(options);
3698
+ getRuntime4().setDefaultModelOptions(options);
3448
3699
  };
3449
3700
  setDefaultModelOption = (key, value) => {
3450
- getRuntime3().setDefaultModelOption(key, value);
3701
+ getRuntime4().setDefaultModelOption(key, value);
3451
3702
  };
3452
3703
  getDefaultModelOptions = () => {
3453
- return getRuntime3().getDefaultModelOptions();
3704
+ return getRuntime4().getDefaultModelOptions();
3454
3705
  };
3455
3706
  getDefaultModelOption = (key, defaultValue) => {
3456
- return getRuntime3().getDefaultModelOption(key, defaultValue);
3707
+ return getRuntime4().getDefaultModelOption(key, defaultValue);
3457
3708
  };
3458
3709
  }
3459
3710
  });
3460
3711
 
3461
3712
  // src/options/data-options.ts
3462
- var getRuntime4, setDataOptions, setDataOption, getDataOptions, getDataSnapshot, getDataOption, getExactDataOption, getDataNames;
3713
+ var getRuntime5, setDataOptions, setDataOption, getDataOptions, getDataSnapshot, getDataOption, getExactDataOption, getDataNames;
3463
3714
  var init_data_options = __esm({
3464
3715
  "src/options/data-options.ts"() {
3465
3716
  init_runtime();
3466
3717
  init_runtime_context();
3467
- getRuntime4 = () => getActiveRuntime() ?? defaultRuntime;
3718
+ getRuntime5 = () => getActiveRuntime() ?? defaultRuntime;
3468
3719
  setDataOptions = (dataName, options) => {
3469
- getRuntime4().setDataOptions(dataName, options);
3720
+ getRuntime5().setDataOptions(dataName, options);
3470
3721
  };
3471
3722
  setDataOption = (dataName, key, value) => {
3472
- getRuntime4().setDataOption(dataName, key, value);
3723
+ getRuntime5().setDataOption(dataName, key, value);
3473
3724
  };
3474
3725
  getDataOptions = (dataName) => {
3475
- return getRuntime4().getDataOptions(dataName);
3726
+ return getRuntime5().getDataOptions(dataName);
3476
3727
  };
3477
3728
  getDataSnapshot = (dataName) => {
3478
- return getRuntime4().getDataSnapshot(dataName);
3729
+ return getRuntime5().getDataSnapshot(dataName);
3479
3730
  };
3480
3731
  getDataOption = (dataName, key, defaultValue) => {
3481
- return getRuntime4().getDataOption(dataName, key, defaultValue);
3732
+ return getRuntime5().getDataOption(dataName, key, defaultValue);
3482
3733
  };
3483
3734
  getExactDataOption = (dataName, key) => {
3484
- return getRuntime4().getExactDataOption(dataName, key);
3735
+ return getRuntime5().getExactDataOption(dataName, key);
3485
3736
  };
3486
3737
  getDataNames = () => {
3487
- return getRuntime4().getDataNames();
3738
+ return getRuntime5().getDataNames();
3488
3739
  };
3489
3740
  }
3490
3741
  });
@@ -3805,10 +4056,12 @@ function resolveServiceAuthorization(input) {
3805
4056
  const listResponse = input.listResponse === true && input.parent === void 0 && (input.applicability ?? "service") === "service" && scopePath.length === 0 && outputAccess.operation === "list" && outputAccess.rowAccess === "list" && queryOutputAccess(outputAccess);
3806
4057
  const responseSnapshots = input.parent && (nestedResponse || readResponse) ? callRecord(input.parent).responseSnapshots : listResponse ? Object.freeze({
3807
4058
  skipOutput: configuration.unsafeSkipListOutputSnapshotChecks === true,
3808
- skipNested: configuration.unsafeSkipListNestedDocumentSnapshotChecks === true
4059
+ skipNested: configuration.unsafeSkipListNestedDocumentSnapshotChecks === true,
4060
+ skipInitialOutputCopy: configuration.unsafeSkipListOutputSnapshotChecks === true && configuration.unsafeSkipListInitialOutputSnapshotCopy === true
3809
4061
  }) : readResponse ? Object.freeze({
3810
4062
  skipOutput: configuration.unsafeSkipReadOutputSnapshotChecks === true,
3811
- skipNested: configuration.unsafeSkipReadNestedDocumentSnapshotChecks === true
4063
+ skipNested: configuration.unsafeSkipReadNestedDocumentSnapshotChecks === true,
4064
+ skipInitialOutputCopy: configuration.unsafeSkipReadOutputSnapshotChecks === true && configuration.unsafeSkipReadInitialOutputSnapshotCopy === true
3812
4065
  }) : void 0;
3813
4066
  const call = Object.freeze(/* @__PURE__ */ Object.create(null));
3814
4067
  calls.set(call, {
@@ -3825,6 +4078,7 @@ function resolveServiceAuthorization(input) {
3825
4078
  nestedResponse,
3826
4079
  responseSnapshots,
3827
4080
  validateOutputSnapshots: responseSnapshots?.skipOutput !== true,
4081
+ skipInitialOutputSnapshotCopy: responseSnapshots?.skipInitialOutputCopy === true,
3828
4082
  validateDocumentSnapshots: !(input.listResponse === true && input.parent === void 0 && (input.applicability ?? "service") === "service" && outputAccess.operation === "list" && outputAccess.rowAccess === "list" && outputAccess.outputAccess === "list" && scopePath.length === 0 && configuration.unsafeSkipListDocumentSnapshotChecks === true || readResponse && configuration.unsafeSkipReadDocumentSnapshotChecks === true || nestedResponse && responseSnapshots?.skipNested === true)
3829
4083
  });
3830
4084
  return call;
@@ -3854,6 +4108,10 @@ function requiresOutputSnapshotChecks(call, binding) {
3854
4108
  assertAuthorizationBinding(call, binding);
3855
4109
  return callRecord(call).validateOutputSnapshots;
3856
4110
  }
4111
+ function skipsInitialOutputSnapshotCopy(call) {
4112
+ const record3 = callRecord(call);
4113
+ return !record3.validateOutputSnapshots && record3.skipInitialOutputSnapshotCopy;
4114
+ }
3857
4115
  function readServiceAuthorizationHydration(call, binding) {
3858
4116
  assertAuthorizationBinding(call, binding);
3859
4117
  return copyAuthorizationValue({ hydration: callRecord(call).configuration.hydration }, true);
@@ -5045,8 +5303,18 @@ function associateDocumentAuthorization(handle, binding, output) {
5045
5303
  authorizationError("output already associated");
5046
5304
  return;
5047
5305
  }
5306
+ if (skipsInitialOutputSnapshotCopy(stage.call) && ordinaryDecisionBinding(binding)) {
5307
+ if (requiresOutputSnapshotChecks(stage.call, binding))
5308
+ authorizationError("output snapshot copy requires skipped comparisons");
5309
+ const identities = tryOutputIdentitiesWithoutSnapshot(output);
5310
+ if (identities) {
5311
+ outputs.set(output, { handle, snapshotState: "omitted", identities, validateSnapshot: false });
5312
+ return;
5313
+ }
5314
+ }
5048
5315
  outputs.set(output, {
5049
5316
  handle,
5317
+ snapshotState: "copied",
5050
5318
  snapshot: copyAuthorizationValue(output, "document"),
5051
5319
  identities: outputIdentities(output),
5052
5320
  validateSnapshot: requiresOutputSnapshotChecks(stage.call, binding)
@@ -5224,10 +5492,11 @@ var init_request_work = __esm({
5224
5492
 
5225
5493
  // src/acl/model-output-planning.ts
5226
5494
  function getCapturedAuthorizationOption(configuration, key) {
5227
- const defaultValue = key.startsWith("operationAccess.") ? (0, import_utils23.get)(configuration.operationAccessDefaults, key.slice("operationAccess.".length)) : void 0;
5228
- return resolveNestedOption((path, fallback) => (0, import_utils23.get)(configuration, path, fallback), key, defaultValue);
5495
+ const defaultValue = key.startsWith("operationAccess.") ? (0, import_utils24.get)(configuration.operationAccessDefaults, key.slice("operationAccess.".length)) : void 0;
5496
+ return resolveNestedOption((path, fallback) => (0, import_utils24.get)(configuration, path, fallback), key, defaultValue);
5229
5497
  }
5230
- function captureModelAuthorizationConfiguration(runtime, modelName, options = runtime.getModelOptions(modelName), globalOptions = runtime.getGlobalOptions()) {
5498
+ function captureModelAuthorizationConfiguration(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime)) {
5499
+ options ??= runtime.getModelOptions(modelName);
5231
5500
  const model = runtime.getModelInstance(modelName);
5232
5501
  if (!model) return authorizationError(`unknown receiving model: ${modelName}`);
5233
5502
  const virtuals = options.virtuals;
@@ -5238,10 +5507,10 @@ function captureModelAuthorizationConfiguration(runtime, modelName, options = ru
5238
5507
  runtime,
5239
5508
  modelName,
5240
5509
  options,
5241
- globalOptions
5510
+ populatePolicyDefaults
5242
5511
  ),
5243
- requireOperationAccessForPopulateDependencies: globalOptions.requireOperationAccessForPopulateDependencies !== false,
5244
- requireOperationAccessForPopulateQueries: globalOptions.requireOperationAccessForPopulateQueries !== false,
5512
+ populatePolicyDefaults,
5513
+ ...resolvePopulatePolicy(options, populatePolicyDefaults),
5245
5514
  permissionSchema: options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema,
5246
5515
  virtuals,
5247
5516
  alwaysSelectFields: options.alwaysSelectFields,
@@ -5258,6 +5527,8 @@ function captureModelAuthorizationConfiguration(runtime, modelName, options = ru
5258
5527
  unsafeSkipReadOutputSnapshotChecks: options.unsafeSkipReadOutputSnapshotChecks === true,
5259
5528
  unsafeSkipListNestedDocumentSnapshotChecks: options.unsafeSkipListNestedDocumentSnapshotChecks === true,
5260
5529
  unsafeSkipReadNestedDocumentSnapshotChecks: options.unsafeSkipReadNestedDocumentSnapshotChecks === true,
5530
+ unsafeSkipListInitialOutputSnapshotCopy: options.unsafeSkipListInitialOutputSnapshotCopy === true,
5531
+ unsafeSkipReadInitialOutputSnapshotCopy: options.unsafeSkipReadInitialOutputSnapshotCopy === true,
5261
5532
  overrideFilter: options.overrideFilter,
5262
5533
  baseFilter: options.baseFilter,
5263
5534
  idField: options.idField,
@@ -5294,25 +5565,26 @@ function planModelOutputForHelper(args) {
5294
5565
  requestedSelect: args.select
5295
5566
  });
5296
5567
  }
5297
- var import_utils23;
5568
+ var import_utils24;
5298
5569
  var init_model_output_planning = __esm({
5299
5570
  "src/acl/model-output-planning.ts"() {
5300
- import_utils23 = require("@web-ts-toolkit/utils");
5571
+ import_utils24 = require("@web-ts-toolkit/utils");
5301
5572
  init_manager();
5302
5573
  init_field_catalog();
5303
5574
  init_authorization_snapshot();
5304
5575
  init_virtual_populate_dependencies();
5305
5576
  init_document_authorization();
5306
5577
  init_output_projection();
5578
+ init_populate_policy2();
5307
5579
  }
5308
5580
  });
5309
5581
 
5310
5582
  // src/core-shared.ts
5311
5583
  function isAndFilter(filter2) {
5312
- return !!filter2 && (0, import_utils24.isPlainObject)(filter2) && Object.keys(filter2).length === 1 && (0, import_utils24.isArray)(filter2.$and);
5584
+ return !!filter2 && (0, import_utils25.isPlainObject)(filter2) && Object.keys(filter2).length === 1 && (0, import_utils25.isArray)(filter2.$and);
5313
5585
  }
5314
5586
  function isMergeableClause(filter2) {
5315
- return !!filter2 && (0, import_utils24.isPlainObject)(filter2) && Object.keys(filter2).every((key) => !key.startsWith("$"));
5587
+ return !!filter2 && (0, import_utils25.isPlainObject)(filter2) && Object.keys(filter2).every((key) => !key.startsWith("$"));
5316
5588
  }
5317
5589
  function optimizeAndFilter(clausesInput) {
5318
5590
  const clauses = [];
@@ -5329,11 +5601,11 @@ function optimizeAndFilter(clausesInput) {
5329
5601
  const dedupeKey = (value) => {
5330
5602
  if (value instanceof RegExp) return `regexp:${JSON.stringify([value.source, value.flags])}`;
5331
5603
  if (value instanceof Date) return `date:${value.getTime()}`;
5332
- if ((0, import_utils24.isArray)(value)) {
5604
+ if ((0, import_utils25.isArray)(value)) {
5333
5605
  const entries = Array.from(value, dedupeKey);
5334
5606
  return entries.every((entry) => entry !== void 0) ? `array:${JSON.stringify(entries)}` : void 0;
5335
5607
  }
5336
- if ((0, import_utils24.isPlainObject)(value)) {
5608
+ if ((0, import_utils25.isPlainObject)(value)) {
5337
5609
  const entries = Object.keys(value).sort().map((key) => [key, dedupeKey(value[key])]);
5338
5610
  return entries.every(([, entry]) => entry !== void 0) ? `object:${JSON.stringify(entries)}` : void 0;
5339
5611
  }
@@ -5363,7 +5635,7 @@ function optimizeAndFilter(clausesInput) {
5363
5635
  }
5364
5636
  let canMerge = true;
5365
5637
  for (const [key, value] of Object.entries(clause)) {
5366
- if ((0, import_utils24.hasOwn)(mergedClause, key) && !(0, import_node_util7.isDeepStrictEqual)(mergedClause[key], value)) {
5638
+ if ((0, import_utils25.hasOwn)(mergedClause, key) && !(0, import_node_util7.isDeepStrictEqual)(mergedClause[key], value)) {
5367
5639
  canMerge = false;
5368
5640
  break;
5369
5641
  }
@@ -5374,24 +5646,24 @@ function optimizeAndFilter(clausesInput) {
5374
5646
  }
5375
5647
  Object.assign(mergedClause, clause);
5376
5648
  }
5377
- const finalClauses = (0, import_utils24.isEmpty)(mergedClause) ? remainingClauses : [mergedClause, ...remainingClauses];
5649
+ const finalClauses = (0, import_utils25.isEmpty)(mergedClause) ? remainingClauses : [mergedClause, ...remainingClauses];
5378
5650
  if (finalClauses.length === 0) return null;
5379
5651
  if (finalClauses.length === 1) return finalClauses[0];
5380
5652
  return { $and: finalClauses };
5381
5653
  }
5382
5654
  function normalizeFilter(filter2) {
5383
5655
  if (filter2 === false) return false;
5384
- if (!filter2 || !(0, import_utils24.isPlainObject)(filter2) || (0, import_utils24.isEmpty)(filter2)) return null;
5656
+ if (!filter2 || !(0, import_utils25.isPlainObject)(filter2) || (0, import_utils25.isEmpty)(filter2)) return null;
5385
5657
  if (!isAndFilter(filter2)) {
5386
5658
  return filter2;
5387
5659
  }
5388
5660
  return optimizeAndFilter(filter2.$and);
5389
5661
  }
5390
5662
  async function resolveIdentifierFilter(req, idField, resolveIdFilter, id) {
5391
- if ((0, import_utils24.isFunction)(resolveIdFilter)) {
5663
+ if ((0, import_utils25.isFunction)(resolveIdFilter)) {
5392
5664
  return await resolveIdFilter.call(req, id);
5393
5665
  }
5394
- if ((0, import_utils24.isString)(idField)) {
5666
+ if ((0, import_utils25.isString)(idField)) {
5395
5667
  return { [idField]: id };
5396
5668
  }
5397
5669
  return { _id: id };
@@ -5415,7 +5687,7 @@ async function resolveAccessFilterParts({
5415
5687
  }
5416
5688
  const overrideFilterFn = getOption(`overrideFilter.${access}`, null);
5417
5689
  const baseFilterFn = rows2.mode === "request" ? getOption(`baseFilter.${access}`, null) : null;
5418
- if (nextFilter !== false && (0, import_utils24.isFunction)(overrideFilterFn)) {
5690
+ if (nextFilter !== false && (0, import_utils25.isFunction)(overrideFilterFn)) {
5419
5691
  nextFilter = normalizeFilter(await overrideFilterFn.call(req, nextFilter, permissions));
5420
5692
  }
5421
5693
  if (nextFilter === false) return { transformed: false, scope: {}, filter: false };
@@ -5423,7 +5695,7 @@ async function resolveAccessFilterParts({
5423
5695
  const scope2 = rows2.mode === "scope" ? rows2.filter : {};
5424
5696
  return { transformed: nextFilter ?? {}, scope: scope2, filter: intersectFilters(nextFilter, scope2) };
5425
5697
  }
5426
- if (!(0, import_utils24.isFunction)(baseFilterFn)) return { transformed: nextFilter ?? {}, scope: {}, filter: nextFilter ?? {} };
5698
+ if (!(0, import_utils25.isFunction)(baseFilterFn)) return { transformed: nextFilter ?? {}, scope: {}, filter: nextFilter ?? {} };
5427
5699
  const cached = cache.get(cacheKey);
5428
5700
  const reusable = cached?.resolver === baseFilterFn;
5429
5701
  const baseFilter = normalizeFilter(
@@ -5458,34 +5730,34 @@ async function setRequestPermissions(req) {
5458
5730
  if (owner === activeRuntime) return;
5459
5731
  if (hasFieldValue && owner === void 0) return;
5460
5732
  const globalPermissions = getGlobalOption("globalPermissions");
5461
- const permissions = (0, import_utils24.isFunction)(globalPermissions) ? await globalPermissions.call(req, req) : void 0;
5462
- if ((0, import_utils24.isPlainObject)(permissions)) req[requestPermissionField] = permissions;
5463
- else if ((0, import_utils24.isArray)(permissions)) req[requestPermissionField] = (0, import_utils24.arrayToRecord)(permissions);
5464
- else if ((0, import_utils24.isString)(permissions)) req[requestPermissionField] = { [permissions]: true };
5733
+ const permissions = (0, import_utils25.isFunction)(globalPermissions) ? await globalPermissions.call(req, req) : void 0;
5734
+ if ((0, import_utils25.isPlainObject)(permissions)) req[requestPermissionField] = permissions;
5735
+ else if ((0, import_utils25.isArray)(permissions)) req[requestPermissionField] = (0, import_utils25.arrayToRecord)(permissions);
5736
+ else if ((0, import_utils25.isString)(permissions)) req[requestPermissionField] = { [permissions]: true };
5465
5737
  else req[requestPermissionField] = {};
5466
5738
  owners.set(requestPermissionField, activeRuntime);
5467
5739
  }
5468
5740
  async function evaluateRouteGuard(req, permissions, routeGuard) {
5469
5741
  const phas = (key) => permissions.has(key);
5470
5742
  const { stringHandler, arrayHandler } = createValidator(phas);
5471
- if ((0, import_utils24.isBoolean)(routeGuard)) {
5743
+ if ((0, import_utils25.isBoolean)(routeGuard)) {
5472
5744
  return routeGuard === true;
5473
5745
  }
5474
- if ((0, import_utils24.isString)(routeGuard)) {
5746
+ if ((0, import_utils25.isString)(routeGuard)) {
5475
5747
  return stringHandler(routeGuard);
5476
5748
  }
5477
- if ((0, import_utils24.isArray)(routeGuard)) {
5749
+ if ((0, import_utils25.isArray)(routeGuard)) {
5478
5750
  return arrayHandler(routeGuard);
5479
5751
  }
5480
- if ((0, import_utils24.isFunction)(routeGuard)) {
5752
+ if ((0, import_utils25.isFunction)(routeGuard)) {
5481
5753
  return routeGuard.call(req, permissions);
5482
5754
  }
5483
5755
  return false;
5484
5756
  }
5485
5757
  async function callHookChain(req, hook, doc, permissions, context) {
5486
- const hooks = (0, import_utils24.castArray)(hook);
5758
+ const hooks = (0, import_utils25.castArray)(hook);
5487
5759
  for (let x = 0; x < hooks.length; x++) {
5488
- if ((0, import_utils24.isFunction)(hooks[x])) {
5760
+ if ((0, import_utils25.isFunction)(hooks[x])) {
5489
5761
  doc = await hooks[x].call(req, doc, permissions, context);
5490
5762
  }
5491
5763
  }
@@ -5505,22 +5777,22 @@ async function collectSchemaFields({
5505
5777
  for (let x = 0; x < keys2.length; x++) {
5506
5778
  const key = keys2[x];
5507
5779
  const value = extractScopedOutputRule(permissionSchema, key, access);
5508
- if ((0, import_utils24.isBoolean)(value)) {
5780
+ if ((0, import_utils25.isBoolean)(value)) {
5509
5781
  if (value) fields.push(key);
5510
- } else if ((0, import_utils24.isString)(value)) {
5782
+ } else if ((0, import_utils25.isString)(value)) {
5511
5783
  if (stringHandler(value)) fields.push(key);
5512
- } else if ((0, import_utils24.isArray)(value)) {
5784
+ } else if ((0, import_utils25.isArray)(value)) {
5513
5785
  if (arrayHandler(value)) fields.push(key);
5514
- } else if ((0, import_utils24.isFunction)(value)) {
5786
+ } else if ((0, import_utils25.isFunction)(value)) {
5515
5787
  if (await value.call(req, ...functionArgs)) fields.push(key);
5516
5788
  }
5517
5789
  }
5518
5790
  return fields;
5519
5791
  }
5520
- var import_utils24, import_node_util7, permissionFieldOwners;
5792
+ var import_utils25, import_node_util7, permissionFieldOwners;
5521
5793
  var init_core_shared = __esm({
5522
5794
  "src/core-shared.ts"() {
5523
- import_utils24 = require("@web-ts-toolkit/utils");
5795
+ import_utils25 = require("@web-ts-toolkit/utils");
5524
5796
  import_node_util7 = require("util");
5525
5797
  init_helpers();
5526
5798
  init_options();
@@ -5772,6 +6044,13 @@ var init_logger_helpers = __esm({
5772
6044
 
5773
6045
  // src/acl/populate-target.ts
5774
6046
  function setPopulateTargetMeta(entry, meta) {
6047
+ if (meta.fetchBinding)
6048
+ Object.defineProperty(entry, "model", {
6049
+ value: meta.fetchBinding.model,
6050
+ enumerable: true,
6051
+ writable: false,
6052
+ configurable: false
6053
+ });
5775
6054
  Object.defineProperty(entry, POPULATE_TARGET_PLAN, {
5776
6055
  value: meta,
5777
6056
  enumerable: false,
@@ -7404,7 +7683,7 @@ init_options();
7404
7683
  init_permission();
7405
7684
 
7406
7685
  // src/services/base.ts
7407
- var import_utils25 = require("@web-ts-toolkit/utils");
7686
+ var import_utils26 = require("@web-ts-toolkit/utils");
7408
7687
  init_options();
7409
7688
  init_helpers();
7410
7689
  init_document();
@@ -7972,14 +8251,111 @@ function isCorrelatedInclude(value) {
7972
8251
  // src/services/base.ts
7973
8252
  init_request_complexity();
7974
8253
 
7975
- // src/acl/model-service-owner.ts
8254
+ // src/model.ts
7976
8255
  var import_node_async_hooks3 = require("async_hooks");
8256
+ var import_utils23 = require("@web-ts-toolkit/utils");
8257
+ init_runtime_context();
8258
+ init_runtime();
8259
+ var capturedModelConstruction = new import_node_async_hooks3.AsyncLocalStorage();
8260
+ function withCapturedPopulateModel(runtime, modelName, model, construct) {
8261
+ return capturedModelConstruction.run({ runtime, modelName, model }, construct);
8262
+ }
8263
+ function admitModelPersistence(adapter, scheduler) {
8264
+ return {
8265
+ modelName: adapter.modelName,
8266
+ mongooseModel: adapter.mongooseModel,
8267
+ new: () => adapter.new(),
8268
+ // Mongoose create(array) otherwise starts all document saves at once. Keep
8269
+ // the adapter's array input/output contract, with one permit per item; all
8270
+ // items are submitted even if one rejects, as with unordered create(array).
8271
+ create: (data) => Array.isArray(data) ? Promise.all(data.map((item) => scheduler.work(async () => (await adapter.create([item]))[0]))) : scheduler.work(() => adapter.create(data)),
8272
+ find: (props) => scheduler.work(() => adapter.find(props)),
8273
+ findOne: (props) => scheduler.work(() => adapter.findOne(props)),
8274
+ exists: (filter2) => scheduler.work(() => adapter.exists(filter2)),
8275
+ countDocuments: (filter2) => scheduler.work(() => adapter.countDocuments(filter2)),
8276
+ distinct: (field, conditions) => scheduler.work(() => adapter.distinct(field, conditions)),
8277
+ aggregate: (pipeline) => scheduler.work(() => adapter.aggregate(pipeline)),
8278
+ // Casting builds no persistence work and must not acquire a recursive permit.
8279
+ ...adapter.castFilter ? { castFilter: (filter2) => adapter.castFilter(filter2) } : {}
8280
+ };
8281
+ }
8282
+ var Model = class {
8283
+ constructor(modelName, runtime) {
8284
+ this.modelName = modelName;
8285
+ this.runtime = runtime ?? null;
8286
+ const resolvedRuntime = runtime ?? getActiveRuntime() ?? defaultRuntime;
8287
+ const captured = capturedModelConstruction.getStore();
8288
+ const registered = captured?.runtime === resolvedRuntime && captured.modelName === modelName ? captured.model : resolvedRuntime.getModelInstance(modelName);
8289
+ if (!registered) {
8290
+ throw new Error(
8291
+ `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this runtime.`
8292
+ );
8293
+ }
8294
+ this.mongooseModel = registered;
8295
+ if (!this.mongooseModel) return;
8296
+ }
8297
+ new() {
8298
+ const doc = new this.mongooseModel();
8299
+ return doc;
8300
+ }
8301
+ create(data) {
8302
+ return this.mongooseModel.create(data);
8303
+ }
8304
+ find({ filter: filter2, select, sort, populate, limit, hardLimit, skip, lean }) {
8305
+ const builder = this.mongooseModel.find(filter2);
8306
+ if (select) builder.select(select);
8307
+ if (skip) builder.skip(Number(skip));
8308
+ const normalizedLimit = Number(limit);
8309
+ if (Number.isSafeInteger(normalizedLimit) && normalizedLimit > 0) {
8310
+ builder.limit(normalizedLimit);
8311
+ } else if (Number.isSafeInteger(hardLimit) && Number(hardLimit) > 0) {
8312
+ builder.limit(Number(hardLimit));
8313
+ }
8314
+ if (sort) builder.sort(sort);
8315
+ if (populate) builder.populate(populate);
8316
+ if (lean) builder.lean();
8317
+ return builder;
8318
+ }
8319
+ findOne({ filter: filter2, select, sort, populate, lean }) {
8320
+ const builder = this.mongooseModel.findOne(filter2);
8321
+ if (select) builder.select(select);
8322
+ if (sort) builder.sort(sort);
8323
+ if (populate) builder.populate(populate);
8324
+ if (lean) builder.lean();
8325
+ return builder;
8326
+ }
8327
+ exists(filter2) {
8328
+ if (!filter2) return null;
8329
+ return this.findOne({ filter: filter2 }).select("_id").lean();
8330
+ }
8331
+ // see https://mongoosejs.com/docs/api.html#query_Query-countDocuments
8332
+ countDocuments(filter2 = {}) {
8333
+ return this.mongooseModel.countDocuments(filter2);
8334
+ }
8335
+ /** Cast a copy using this model's query schema/setters, without executing query middleware or persistence. */
8336
+ castFilter(filter2) {
8337
+ const query = this.mongooseModel.countDocuments((0, import_utils23.cloneDeep)(filter2));
8338
+ return query.cast(this.mongooseModel);
8339
+ }
8340
+ // see https://mongoosejs.com/docs/api.html#model_Model.distinct
8341
+ distinct(field, conditions = {}) {
8342
+ return this.mongooseModel.distinct(field, conditions);
8343
+ }
8344
+ aggregate(pipeline) {
8345
+ return this.mongooseModel.aggregate(pipeline);
8346
+ }
8347
+ };
8348
+ var model_default = Model;
8349
+
8350
+ // src/acl/model-service-owner.ts
8351
+ var import_node_async_hooks4 = require("async_hooks");
7977
8352
  init_runtime();
7978
8353
  init_runtime_context();
8354
+ init_populate_policy2();
7979
8355
  var cores = /* @__PURE__ */ new WeakMap();
7980
- var construction = new import_node_async_hooks3.AsyncLocalStorage();
7981
- var dispatch = new import_node_async_hooks3.AsyncLocalStorage();
7982
- var operationGuard = new import_node_async_hooks3.AsyncLocalStorage();
8356
+ var construction = new import_node_async_hooks4.AsyncLocalStorage();
8357
+ var dispatch = new import_node_async_hooks4.AsyncLocalStorage();
8358
+ var operationGuard = new import_node_async_hooks4.AsyncLocalStorage();
7983
8359
  function withCapturedModelOperationGuard(core, modelName, access, guard2, permissions, run) {
7984
8360
  return operationGuard.run({ captured: { core, modelName, access, guard: guard2, permissions } }, run);
7985
8361
  }
@@ -8028,15 +8404,16 @@ function bindModelOwnerMethods(receiver, runtime) {
8028
8404
  }
8029
8405
  }
8030
8406
  }
8031
- function modelServiceOptions(receiver, read) {
8407
+ function modelServiceOptions(receiver, runtime, read) {
8408
+ modelServicePopulatePolicyDefaults(receiver, runtime);
8032
8409
  const call = dispatch.getStore();
8033
8410
  if (call?.receiver !== receiver) return read();
8034
8411
  return call.options ??= read();
8035
8412
  }
8036
- function modelServiceGlobalOptions(receiver, runtime) {
8413
+ function modelServicePopulatePolicyDefaults(receiver, runtime) {
8037
8414
  const call = dispatch.getStore();
8038
- if (call?.receiver !== receiver) return runtime.getGlobalOptions();
8039
- return call.globalOptions ??= runtime.getGlobalOptions();
8415
+ if (call?.receiver !== receiver) return capturePopulatePolicyDefaults(runtime);
8416
+ return call.populatePolicyDefaults ??= capturePopulatePolicyDefaults(runtime);
8040
8417
  }
8041
8418
 
8042
8419
  // src/services/base.ts
@@ -8190,27 +8567,6 @@ function castCountGroups(input, values) {
8190
8567
  // src/services/base.ts
8191
8568
  init_service_authorization();
8192
8569
 
8193
- // src/meta.ts
8194
- init_runtime();
8195
- init_runtime_context();
8196
- var getRuntime5 = () => getActiveRuntime() ?? defaultRuntime;
8197
- var getModelRef = (modelName, refPath, runtime = getRuntime5()) => {
8198
- const direct = runtime.getModelRef(modelName, refPath);
8199
- if (direct) return direct;
8200
- if (!refPath.includes(".")) return null;
8201
- try {
8202
- const instance = runtime.getModelInstance?.(
8203
- modelName
8204
- );
8205
- const schemaPath = instance?.schema?.path?.(refPath);
8206
- const element = schemaPath?.$embeddedSchemaType ?? schemaPath?.embeddedSchemaType ?? schemaPath?.caster;
8207
- const ref = schemaPath?.options?.ref ?? element?.options?.ref ?? null;
8208
- return typeof ref === "string" && ref.length > 0 ? ref : null;
8209
- } catch {
8210
- return null;
8211
- }
8212
- };
8213
-
8214
8570
  // src/acl/related-execution.ts
8215
8571
  init_public_admission();
8216
8572
  init_model_output_planning();
@@ -8458,9 +8814,9 @@ function resolveExistsOptions(service, options = {}) {
8458
8814
 
8459
8815
  // src/services/model-service-intent.ts
8460
8816
  function captureModelServiceIntent(owner, method, args = {}, options = {}) {
8461
- const defaults = owner.defaults;
8817
+ const defaults2 = owner.defaults;
8462
8818
  const posture = owner.getPermissionsPosture();
8463
- const service = { defaults, getPermissionsPosture: () => posture };
8819
+ const service = { defaults: defaults2, getPermissionsPosture: () => posture };
8464
8820
  switch (method) {
8465
8821
  case "find":
8466
8822
  return deepIsolateValue({ args: resolveFindArgs(service, args), options: resolveFindOptions(service, options) });
@@ -8491,6 +8847,7 @@ function captureModelServiceIntent(owner, method, args = {}, options = {}) {
8491
8847
  }
8492
8848
 
8493
8849
  // src/acl/related-execution.ts
8850
+ init_populate_policy2();
8494
8851
  init_service_authorization();
8495
8852
  function staticObjectIdReference(runtime, source, path, target) {
8496
8853
  const model = runtime.getModelInstance(source), related = runtime.getModelInstance(target);
@@ -8507,7 +8864,7 @@ function staticObjectIdReference(runtime, source, path, target) {
8507
8864
  const scalar = type?.instance === "Array" ? type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster : type;
8508
8865
  return scalar?.instance === "ObjectId" && (type?.options?.ref ?? scalar.options?.ref) === target && type?.options?.refPath === void 0 && scalar.options?.refPath === void 0;
8509
8866
  }
8510
- function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalOptions = runtime.getGlobalOptions()) {
8867
+ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime)) {
8511
8868
  if (depth > 32) authorizationError("related descriptor depth exceeded");
8512
8869
  assertPublicAdmission(args.populate, "populate");
8513
8870
  assertPublicAdmission(args.include, "include");
@@ -8516,20 +8873,32 @@ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalO
8516
8873
  for (const entry of entries(args.populate)) {
8517
8874
  const path = typeof entry === "string" ? entry : entry.path;
8518
8875
  if (typeof entry !== "string") assertPopulateAccess(entry.access);
8519
- const model = getModelRef(modelName, path, runtime);
8520
- if (model) {
8521
- const target = capturePopulateTargetConfiguration(runtime, model, `${modelName}.${path}`);
8876
+ const target = capturePopulateTargetBinding(runtime, modelName, path);
8877
+ if (target) {
8522
8878
  targets.push({
8523
8879
  path,
8524
- modelName: model,
8525
- configuration: captureModelAuthorizationConfiguration(runtime, model, target.options, globalOptions),
8526
- staticObjectIdReference: staticObjectIdReference(runtime, modelName, path, model)
8880
+ modelName: target.modelName,
8881
+ model: target.model,
8882
+ configuration: captureModelAuthorizationConfiguration(
8883
+ runtime,
8884
+ target.modelName,
8885
+ target.options,
8886
+ populatePolicyDefaults
8887
+ ),
8888
+ staticObjectIdReference: staticObjectIdReference(runtime, modelName, path, target.modelName)
8527
8889
  });
8528
8890
  }
8529
8891
  }
8530
8892
  for (const entry of entries(args.include)) {
8531
8893
  if (!runtime.hasModel(entry.model)) authorizationError(`Model ${entry.model} not found`);
8532
- const configuration = captureModelAuthorizationConfiguration(runtime, entry.model, void 0, globalOptions);
8894
+ const model = runtime.getModelInstance(entry.model);
8895
+ if (!model) authorizationError(`unknown receiving model: ${entry.model}`);
8896
+ const configuration = captureModelAuthorizationConfiguration(
8897
+ runtime,
8898
+ entry.model,
8899
+ void 0,
8900
+ populatePolicyDefaults
8901
+ );
8533
8902
  const queryIntent = entry.op === "count" ? void 0 : captureModelServiceIntent(
8534
8903
  {
8535
8904
  defaults: configuration.defaults ?? {},
@@ -8551,6 +8920,7 @@ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalO
8551
8920
  targets.push({
8552
8921
  path: entry.path,
8553
8922
  modelName: entry.model,
8923
+ model,
8554
8924
  kind: entry.op === "count" ? "count" : "output",
8555
8925
  configuration,
8556
8926
  queryIntent,
@@ -8560,7 +8930,7 @@ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalO
8560
8930
  entry.model,
8561
8931
  queryIntent?.args ?? entry.args ?? {},
8562
8932
  depth + 1,
8563
- globalOptions
8933
+ populatePolicyDefaults
8564
8934
  )
8565
8935
  });
8566
8936
  }
@@ -8577,7 +8947,8 @@ function createRelatedExecution(receiver, access, parent, binding, path) {
8577
8947
  const captured = readServiceAuthorization(parent, binding);
8578
8948
  const target = captured.relatedTargets.find((entry) => entry.path === path);
8579
8949
  const policy = captured.authorization.related[path];
8580
- if ((target || policy) && (!target || target.modelName !== getServiceExecutors(receiver).binding().modelName))
8950
+ const receiving = getServiceExecutors(receiver).binding();
8951
+ if (policy && !target || target && (target.modelName !== receiving.modelName || target.model !== void 0 && target.model !== receiving.model))
8581
8952
  authorizationError(`related model mismatch: ${path}`);
8582
8953
  const execution = createServiceExecution(
8583
8954
  receiver,
@@ -8712,20 +9083,20 @@ var copyAuthorizedOutput = (value) => {
8712
9083
  transferDocumentAuthorizationGraph(value, copy);
8713
9084
  return copy;
8714
9085
  };
8715
- var isVirtualContainerValueForGuard = (value) => (0, import_utils25.isPlainObject)(value) && "sub" in value;
9086
+ var isVirtualContainerValueForGuard = (value) => (0, import_utils26.isPlainObject)(value) && "sub" in value;
8716
9087
  var getScopeVirtualsForGuard = (rootVirtuals, scopePath) => {
8717
- if (!rootVirtuals || !(0, import_utils25.isPlainObject)(rootVirtuals)) return null;
9088
+ if (!rootVirtuals || !(0, import_utils26.isPlainObject)(rootVirtuals)) return null;
8718
9089
  if (scopePath.length === 0) return rootVirtuals;
8719
9090
  let current = rootVirtuals;
8720
9091
  for (let i = 0; i < scopePath.length; i += 2) {
8721
9092
  const field = scopePath[i];
8722
9093
  const subMarker = scopePath[i + 1];
8723
9094
  if (!field || subMarker !== "sub") return null;
8724
- if (!(0, import_utils25.isPlainObject)(current)) return null;
9095
+ if (!(0, import_utils26.isPlainObject)(current)) return null;
8725
9096
  const container = current[field];
8726
9097
  if (!isVirtualContainerValueForGuard(container)) return null;
8727
9098
  current = container.sub;
8728
- if (!(0, import_utils25.isPlainObject)(current)) return null;
9099
+ if (!(0, import_utils26.isPlainObject)(current)) return null;
8729
9100
  }
8730
9101
  return current;
8731
9102
  };
@@ -8791,7 +9162,7 @@ var sanitizeSubScopeVirtualKeys = (data, snapshot, sub) => {
8791
9162
  for (const entry of value) stripScope(entry, currentScope);
8792
9163
  return;
8793
9164
  }
8794
- if (!(0, import_utils25.isPlainObject)(value)) return;
9165
+ if (!(0, import_utils26.isPlainObject)(value)) return;
8795
9166
  const record3 = value;
8796
9167
  const leaves = getScopeVirtualLeafNames(snapshot, currentScope);
8797
9168
  for (const leaf of leaves) {
@@ -8804,7 +9175,7 @@ var sanitizeSubScopeVirtualKeys = (data, snapshot, sub) => {
8804
9175
  for (const key of Object.keys(record3)) {
8805
9176
  if (leaves.has(key) || containers.has(key)) continue;
8806
9177
  const child = record3[key];
8807
- if (Array.isArray(child) || (0, import_utils25.isPlainObject)(child)) {
9178
+ if (Array.isArray(child) || (0, import_utils26.isPlainObject)(child)) {
8808
9179
  stripScope(child, currentScope);
8809
9180
  }
8810
9181
  }
@@ -8816,7 +9187,7 @@ var LOGICAL_FILTER_KEYS = /* @__PURE__ */ new Set(["$and", "$or", "$nor"]);
8816
9187
  var isOperatorKey = (key) => key.startsWith("$");
8817
9188
  var REMOVED_VIRTUAL_FILTER = /* @__PURE__ */ Symbol("removed virtual filter clause");
8818
9189
  var rewriteFilterObject = (value, visit) => {
8819
- if (!(0, import_utils25.isPlainObject)(value)) return value;
9190
+ if (!(0, import_utils26.isPlainObject)(value)) return value;
8820
9191
  let changed = false;
8821
9192
  const entries = [];
8822
9193
  for (const [key, child] of Object.entries(value)) {
@@ -8847,7 +9218,7 @@ var resolveVirtualFilterField = (path, scope2) => {
8847
9218
  if (!Object.hasOwn(scope2, segment) || scope2[segment] === void 0) return null;
8848
9219
  const definition = scope2[segment];
8849
9220
  if (!isVirtualContainerValueForGuard(definition)) return REMOVED_VIRTUAL_FILTER;
8850
- scope2 = (0, import_utils25.isPlainObject)(definition.sub) ? definition.sub : null;
9221
+ scope2 = (0, import_utils26.isPlainObject)(definition.sub) ? definition.sub : null;
8851
9222
  inContainer = true;
8852
9223
  }
8853
9224
  return scope2;
@@ -8859,7 +9230,7 @@ var stripVirtualFilterOperator = (key, value, scope2) => {
8859
9230
  }
8860
9231
  if (key === "$all") {
8861
9232
  return rewriteFilterClauses(value, (entry) => {
8862
- if (!(0, import_utils25.isPlainObject)(entry) || Object.keys(entry).length !== 1 || !Object.hasOwn(entry, "$elemMatch")) return entry;
9233
+ if (!(0, import_utils26.isPlainObject)(entry) || Object.keys(entry).length !== 1 || !Object.hasOwn(entry, "$elemMatch")) return entry;
8863
9234
  return rewriteFilterObject(entry, (operator, operand) => stripVirtualFilterOperator(operator, operand, scope2));
8864
9235
  });
8865
9236
  }
@@ -8874,7 +9245,7 @@ var stripVirtualFilterQuery = (value, scope2, element = false) => {
8874
9245
  if (isOperatorKey(key)) return element ? stripVirtualFilterOperator(key, child, scope2) : child;
8875
9246
  const fieldScope = resolveVirtualFilterField(key, scope2);
8876
9247
  if (fieldScope === REMOVED_VIRTUAL_FILTER) return REMOVED_VIRTUAL_FILTER;
8877
- if (!fieldScope || !(0, import_utils25.isPlainObject)(child)) return child;
9248
+ if (!fieldScope || !(0, import_utils26.isPlainObject)(child)) return child;
8878
9249
  if (Object.keys(child).some(isOperatorKey)) {
8879
9250
  return rewriteFilterObject(
8880
9251
  child,
@@ -8896,9 +9267,9 @@ var stripSubVirtualKeysFromFilter = (filter2, snapshot, sub) => {
8896
9267
  function getCorrelatedTemplateDepth(includes) {
8897
9268
  let max = 0;
8898
9269
  const visit = (entries, depth) => {
8899
- const list = (0, import_utils25.castArray)(entries).filter(Boolean);
9270
+ const list = (0, import_utils26.castArray)(entries).filter(Boolean);
8900
9271
  for (const entry of list) {
8901
- if (!(0, import_utils25.isPlainObject)(entry)) continue;
9272
+ if (!(0, import_utils26.isPlainObject)(entry)) continue;
8902
9273
  max = Math.max(max, depth);
8903
9274
  const nested = entry.args?.include;
8904
9275
  if (nested !== void 0) {
@@ -8923,11 +9294,11 @@ function validateClientFilter(filter2) {
8923
9294
  }
8924
9295
  const blockedOperators = /* @__PURE__ */ new Set(["$where", "$expr", "$function", "$accumulator"]);
8925
9296
  const visit = (value, path) => {
8926
- if ((0, import_utils25.isArray)(value)) {
9297
+ if ((0, import_utils26.isArray)(value)) {
8927
9298
  value.forEach((item, index) => visit(item, `${path}[${index}]`));
8928
9299
  return;
8929
9300
  }
8930
- if (!(0, import_utils25.isPlainObject)(value)) return;
9301
+ if (!(0, import_utils26.isPlainObject)(value)) return;
8931
9302
  Object.entries(value).forEach(([key, child]) => {
8932
9303
  const nextPath = path ? `${path}.${key}` : key;
8933
9304
  if (blockedOperators.has(key)) {
@@ -9075,34 +9446,37 @@ var Base = class {
9075
9446
  });
9076
9447
  }
9077
9448
  async getAuthorizedTargetService(modelName, op, path, parentAuthorization) {
9078
- if (hasModelCoreOwner(this.requestCore) && !this.requestRuntime.hasModel(modelName)) {
9449
+ const binding = parentAuthorization ? this.relatedBinding() : void 0;
9450
+ const captured = parentAuthorization ? readServiceAuthorization(parentAuthorization, binding) : void 0;
9451
+ const target = captured?.relatedTargets.find((entry) => entry.path === path);
9452
+ const policy = path ? captured?.authorization.related[path] : void 0;
9453
+ if (target && target.modelName !== modelName)
9454
+ this.throwClientRequestError("bad_request" /* BadRequest */, `related model mismatch: ${path}`);
9455
+ if (hasModelCoreOwner(this.requestCore) && !target?.model && !this.requestRuntime.hasModel(modelName)) {
9079
9456
  this.throwClientRequestError("bad_request" /* BadRequest */, `Model ${modelName} not found`);
9080
9457
  }
9081
- const policy = path ? relatedPolicy(parentAuthorization, this.relatedBinding(), path) : void 0;
9082
- const captured = parentAuthorization ? readServiceAuthorization(parentAuthorization, this.relatedBinding()) : void 0;
9083
- const target = captured?.relatedTargets.find((entry) => entry.path === path);
9084
9458
  const allowed = policy?.operation.mode === "grant" || (target ? await getRequestWorkState(this.req, this.requestRuntime).hookGate.run(
9085
9459
  () => withCapturedModelOperationGuard(
9086
9460
  this.requestCore,
9087
9461
  modelName,
9088
9462
  op,
9089
9463
  target.operationGuard,
9090
- getAuthorizationPermissions(parentAuthorization, this.relatedBinding()),
9464
+ getAuthorizationPermissions(parentAuthorization, binding),
9091
9465
  () => this.requestCore.isAllowed(modelName, op)
9092
9466
  )
9093
9467
  ) : await this.requestCore.isAllowed(modelName, op));
9094
9468
  if (!allowed) {
9095
9469
  this.throwClientRequestError("unauthorized" /* Unauthorized */, "Unauthorized");
9096
9470
  }
9097
- return this.requestCore.getPublicService(modelName);
9471
+ return target?.model ? withCapturedPopulateModel(
9472
+ this.requestRuntime,
9473
+ modelName,
9474
+ target.model,
9475
+ () => this.requestCore.getPublicService(modelName)
9476
+ ) : this.requestCore.getPublicService(modelName);
9098
9477
  }
9099
9478
  relatedBinding() {
9100
- return {
9101
- request: this.req,
9102
- runtime: this.requestRuntime,
9103
- model: this.requestRuntime.getModelInstance(this.modelName),
9104
- modelName: this.modelName
9105
- };
9479
+ return getServiceExecutors(this).binding();
9106
9480
  }
9107
9481
  relatedExecution(svc, include, parentAuthorization) {
9108
9482
  const op = include.op;
@@ -9132,7 +9506,7 @@ var Base = class {
9132
9506
  }
9133
9507
  processInclude(include, authorization) {
9134
9508
  assertPublicAdmission(include, "include");
9135
- const items = (0, import_utils25.compact)((0, import_utils25.castArray)(include));
9509
+ const items = (0, import_utils26.compact)((0, import_utils26.castArray)(include));
9136
9510
  const legacy = [];
9137
9511
  const correlated = [];
9138
9512
  const correlatedReferenceFields = [];
@@ -9168,23 +9542,23 @@ var Base = class {
9168
9542
  else this.assertIncludeOutputPaths([...legacy, ...correlated]);
9169
9543
  let includeLocalFields = [];
9170
9544
  let includePaths = [];
9171
- (0, import_utils25.forEach)(legacy, (inc) => {
9545
+ (0, import_utils26.forEach)(legacy, (inc) => {
9172
9546
  includeLocalFields.push(inc.localField);
9173
9547
  includePaths.push(inc.path);
9174
9548
  });
9175
- includeLocalFields = (0, import_utils25.uniq)((0, import_utils25.compact)(includeLocalFields));
9176
- includePaths = (0, import_utils25.uniq)((0, import_utils25.compact)(includePaths));
9549
+ includeLocalFields = (0, import_utils26.uniq)((0, import_utils26.compact)(includeLocalFields));
9550
+ includePaths = (0, import_utils26.uniq)((0, import_utils26.compact)(includePaths));
9177
9551
  return {
9178
9552
  includes: legacy,
9179
9553
  correlatedIncludes: correlated,
9180
9554
  includeLocalFields,
9181
9555
  includePaths,
9182
- correlatedReferenceFields: (0, import_utils25.uniq)((0, import_utils25.compact)(correlatedReferenceFields))
9556
+ correlatedReferenceFields: (0, import_utils26.uniq)((0, import_utils26.compact)(correlatedReferenceFields))
9183
9557
  };
9184
9558
  }
9185
9559
  validateIncludeOutputPath(path, modelName, configuration) {
9186
9560
  const permissionField = configuration ? configuration.documentPermissionField ?? "_permissions" : getModelOption(modelName, "documentPermissionField");
9187
- if ((0, import_utils25.get)((0, import_utils25.set)({}, path, true), permissionField) !== void 0 || (0, import_utils25.get)((0, import_utils25.set)({}, permissionField, true), path) !== void 0) {
9561
+ if ((0, import_utils26.get)((0, import_utils26.set)({}, path, true), permissionField) !== void 0 || (0, import_utils26.get)((0, import_utils26.set)({}, permissionField, true), path) !== void 0) {
9188
9562
  this.throwClientRequestError(
9189
9563
  "bad_request" /* BadRequest */,
9190
9564
  `Include output path ${path} overlaps document permission field ${permissionField} on model ${modelName}`
@@ -9209,9 +9583,9 @@ var Base = class {
9209
9583
  const walk = (node, prefix) => {
9210
9584
  for (const [key, value] of Object.entries(node)) {
9211
9585
  if (value === void 0) continue;
9212
- if ((0, import_utils25.isPlainObject)(value) && "sub" in value) {
9586
+ if ((0, import_utils26.isPlainObject)(value) && "sub" in value) {
9213
9587
  const sub = value.sub;
9214
- if ((0, import_utils25.isPlainObject)(sub)) walk(sub, prefix ? `${prefix}.${key}` : key);
9588
+ if ((0, import_utils26.isPlainObject)(sub)) walk(sub, prefix ? `${prefix}.${key}` : key);
9215
9589
  continue;
9216
9590
  }
9217
9591
  out.push(prefix ? `${prefix}.${key}` : key);
@@ -9264,7 +9638,7 @@ var Base = class {
9264
9638
  this.throwClientRequestError("bad_request" /* BadRequest */, `Model ${modelName} not found`);
9265
9639
  }
9266
9640
  for (const entry of entries) {
9267
- if (!(0, import_utils25.isPlainObject)(entry)) continue;
9641
+ if (!(0, import_utils26.isPlainObject)(entry)) continue;
9268
9642
  const models = visited.get(entry) ?? /* @__PURE__ */ new Set();
9269
9643
  if (models.has(modelName)) continue;
9270
9644
  models.add(modelName);
@@ -9277,7 +9651,7 @@ var Base = class {
9277
9651
  const target = targets?.find((target2) => target2.path === entry.path);
9278
9652
  if (nested)
9279
9653
  pending.push({
9280
- entries: (0, import_utils25.compact)((0, import_utils25.castArray)(nested)),
9654
+ entries: (0, import_utils26.compact)((0, import_utils26.castArray)(nested)),
9281
9655
  modelName: entry.model,
9282
9656
  configuration: target?.configuration,
9283
9657
  targets: target?.relatedTargets
@@ -9287,7 +9661,7 @@ var Base = class {
9287
9661
  }
9288
9662
  }
9289
9663
  getForeignKeyValues(value) {
9290
- return (0, import_utils25.flatten)((0, import_utils25.castArray)(value));
9664
+ return (0, import_utils26.flatten)((0, import_utils26.castArray)(value));
9291
9665
  }
9292
9666
  getForeignKey(value) {
9293
9667
  return String(value);
@@ -9295,7 +9669,7 @@ var Base = class {
9295
9669
  buildForeignKeyIndex(rows2, foreignField) {
9296
9670
  const index = /* @__PURE__ */ new Map();
9297
9671
  for (const row of rows2) {
9298
- for (const value of this.getForeignKeyValues((0, import_utils25.get)(row, foreignField))) {
9672
+ for (const value of this.getForeignKeyValues((0, import_utils26.get)(row, foreignField))) {
9299
9673
  const key = this.getForeignKey(value);
9300
9674
  const values = index.get(key);
9301
9675
  if (values) values.push(row);
@@ -9331,9 +9705,9 @@ var Base = class {
9331
9705
  async includeDocs(docs, include, parentAuthorization) {
9332
9706
  assertPublicAdmission(include, "include");
9333
9707
  if (!include) return docs;
9334
- const includes = (0, import_utils25.compact)((0, import_utils25.castArray)(include));
9708
+ const includes = (0, import_utils26.compact)((0, import_utils26.castArray)(include));
9335
9709
  if (includes.length === 0) return docs;
9336
- const isSingle = !(0, import_utils25.isArray)(docs);
9710
+ const isSingle = !(0, import_utils26.isArray)(docs);
9337
9711
  let docList = (isSingle ? [docs] : docs).map(prepareIncludeOutput);
9338
9712
  for (let x = 0; x < includes.length; x++) {
9339
9713
  const include2 = includes[x];
@@ -9363,7 +9737,7 @@ var Base = class {
9363
9737
  const svc = await this.getAuthorizedTargetService(model, "read", path, parentAuthorization);
9364
9738
  for (let y = 0; y < docs.length; y++) {
9365
9739
  const doc = docs[y];
9366
- const localValue = (0, import_utils25.get)(doc, localField);
9740
+ const localValue = (0, import_utils26.get)(doc, localField);
9367
9741
  const execution = this.relatedExecution(svc, include, parentAuthorization);
9368
9742
  const prepared = await prepareModelQuery(
9369
9743
  svc,
@@ -9398,15 +9772,15 @@ var Base = class {
9398
9772
  const { model, op, path, localField, foreignField, filter: _filters, args = {}, options = {} } = include;
9399
9773
  const svc = await this.getAuthorizedTargetService(model, op, path, parentAuthorization);
9400
9774
  const includeLocalValues = [];
9401
- (0, import_utils25.forEach)(docs, (doc) => {
9402
- includeLocalValues.push(...this.getForeignKeyValues((0, import_utils25.get)(doc, localField)));
9775
+ (0, import_utils26.forEach)(docs, (doc) => {
9776
+ includeLocalValues.push(...this.getForeignKeyValues((0, import_utils26.get)(doc, localField)));
9403
9777
  });
9404
9778
  const execution = this.relatedExecution(svc, include, parentAuthorization);
9405
9779
  const prepared = await prepareModelQuery(
9406
9780
  svc,
9407
9781
  execution,
9408
9782
  { kind: "client-read", filter: _filters ?? {} },
9409
- { [foreignField]: { $in: (0, import_utils25.flatten)(includeLocalValues) } },
9783
+ { [foreignField]: { $in: (0, import_utils26.flatten)(includeLocalValues) } },
9410
9784
  true
9411
9785
  );
9412
9786
  const trustedArgs = this.sanitizeIncludeArgs(args, "list");
@@ -9449,7 +9823,7 @@ var Base = class {
9449
9823
  }
9450
9824
  for (let y = 0; y < docs.length; y++) {
9451
9825
  const doc = docs[y];
9452
- const matches = this.getIndexedMatches(index, (0, import_utils25.get)(doc, localField));
9826
+ const matches = this.getIndexedMatches(index, (0, import_utils26.get)(doc, localField));
9453
9827
  const isolated = matches.map((m) => copyAuthorizedOutput(m));
9454
9828
  attachIncludeOutput(doc, path, op === "list" ? isolated : isolated[0]);
9455
9829
  }
@@ -9458,7 +9832,7 @@ var Base = class {
9458
9832
  async includeDocsCount(docs, include, parentAuthorization) {
9459
9833
  const { model, path, localField, foreignField, filter: _filters } = include;
9460
9834
  const svc = await this.getAuthorizedTargetService(model, "count", path, parentAuthorization);
9461
- const groups = prepareCountGroups(docs, (doc) => (0, import_utils25.get)(doc, localField));
9835
+ const groups = prepareCountGroups(docs, (doc) => (0, import_utils26.get)(doc, localField));
9462
9836
  const execution = this.relatedExecution(svc, include, parentAuthorization);
9463
9837
  const prepared = await prepareModelQuery(
9464
9838
  svc,
@@ -9512,7 +9886,7 @@ var Base = class {
9512
9886
  }
9513
9887
  const state = this.getCorrelatedExecState();
9514
9888
  docs = docs.map(prepareIncludeOutput);
9515
- const resolvedSnapshots = snapshots2 ?? docs.map((doc) => (0, import_utils25.cloneDeep)(toObject(getIncludeSource(doc))));
9889
+ const resolvedSnapshots = snapshots2 ?? docs.map((doc) => (0, import_utils26.cloneDeep)(toObject(getIncludeSource(doc))));
9516
9890
  for (const include of correlatedIncludes) {
9517
9891
  switch (include.op) {
9518
9892
  case "read":
@@ -9861,10 +10235,10 @@ var Base = class {
9861
10235
  }
9862
10236
  let ret = result2.data;
9863
10237
  if (sqOptions.path) {
9864
- ret = (0, import_utils25.isArray)(ret) ? (0, import_utils25.flatten)(ret.map((v) => (0, import_utils25.get)(v, sqOptions.path))) : (0, import_utils25.get)(ret, sqOptions.path);
10238
+ ret = (0, import_utils26.isArray)(ret) ? (0, import_utils26.flatten)(ret.map((v) => (0, import_utils26.get)(v, sqOptions.path))) : (0, import_utils26.get)(ret, sqOptions.path);
9865
10239
  }
9866
10240
  if (sqOptions.compact) {
9867
- ret = (0, import_utils25.compact)((0, import_utils25.castArray)(ret));
10241
+ ret = (0, import_utils26.compact)((0, import_utils26.castArray)(ret));
9868
10242
  }
9869
10243
  return ret;
9870
10244
  }
@@ -9879,96 +10253,6 @@ var Base = class {
9879
10253
  var import_utils36 = require("@web-ts-toolkit/utils");
9880
10254
  var import_just_diff = require("just-diff");
9881
10255
 
9882
- // src/model.ts
9883
- var import_utils26 = require("@web-ts-toolkit/utils");
9884
- init_runtime_context();
9885
- init_runtime();
9886
- function admitModelPersistence(adapter, scheduler) {
9887
- return {
9888
- modelName: adapter.modelName,
9889
- mongooseModel: adapter.mongooseModel,
9890
- new: () => adapter.new(),
9891
- // Mongoose create(array) otherwise starts all document saves at once. Keep
9892
- // the adapter's array input/output contract, with one permit per item; all
9893
- // items are submitted even if one rejects, as with unordered create(array).
9894
- create: (data) => Array.isArray(data) ? Promise.all(data.map((item) => scheduler.work(async () => (await adapter.create([item]))[0]))) : scheduler.work(() => adapter.create(data)),
9895
- find: (props) => scheduler.work(() => adapter.find(props)),
9896
- findOne: (props) => scheduler.work(() => adapter.findOne(props)),
9897
- exists: (filter2) => scheduler.work(() => adapter.exists(filter2)),
9898
- countDocuments: (filter2) => scheduler.work(() => adapter.countDocuments(filter2)),
9899
- distinct: (field, conditions) => scheduler.work(() => adapter.distinct(field, conditions)),
9900
- aggregate: (pipeline) => scheduler.work(() => adapter.aggregate(pipeline)),
9901
- // Casting builds no persistence work and must not acquire a recursive permit.
9902
- ...adapter.castFilter ? { castFilter: (filter2) => adapter.castFilter(filter2) } : {}
9903
- };
9904
- }
9905
- var Model = class {
9906
- constructor(modelName, runtime) {
9907
- this.modelName = modelName;
9908
- this.runtime = runtime ?? null;
9909
- const resolvedRuntime = runtime ?? getActiveRuntime() ?? defaultRuntime;
9910
- const registered = resolvedRuntime.getModelInstance(modelName);
9911
- if (!registered) {
9912
- throw new Error(
9913
- `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this runtime.`
9914
- );
9915
- }
9916
- this.mongooseModel = registered;
9917
- if (!this.mongooseModel) return;
9918
- }
9919
- new() {
9920
- const doc = new this.mongooseModel();
9921
- return doc;
9922
- }
9923
- create(data) {
9924
- return this.mongooseModel.create(data);
9925
- }
9926
- find({ filter: filter2, select, sort, populate, limit, hardLimit, skip, lean }) {
9927
- const builder = this.mongooseModel.find(filter2);
9928
- if (select) builder.select(select);
9929
- if (skip) builder.skip(Number(skip));
9930
- const normalizedLimit = Number(limit);
9931
- if (Number.isSafeInteger(normalizedLimit) && normalizedLimit > 0) {
9932
- builder.limit(normalizedLimit);
9933
- } else if (Number.isSafeInteger(hardLimit) && Number(hardLimit) > 0) {
9934
- builder.limit(Number(hardLimit));
9935
- }
9936
- if (sort) builder.sort(sort);
9937
- if (populate) builder.populate(populate);
9938
- if (lean) builder.lean();
9939
- return builder;
9940
- }
9941
- findOne({ filter: filter2, select, sort, populate, lean }) {
9942
- const builder = this.mongooseModel.findOne(filter2);
9943
- if (select) builder.select(select);
9944
- if (sort) builder.sort(sort);
9945
- if (populate) builder.populate(populate);
9946
- if (lean) builder.lean();
9947
- return builder;
9948
- }
9949
- exists(filter2) {
9950
- if (!filter2) return null;
9951
- return this.findOne({ filter: filter2 }).select("_id").lean();
9952
- }
9953
- // see https://mongoosejs.com/docs/api.html#query_Query-countDocuments
9954
- countDocuments(filter2 = {}) {
9955
- return this.mongooseModel.countDocuments(filter2);
9956
- }
9957
- /** Cast a copy using this model's query schema/setters, without executing query middleware or persistence. */
9958
- castFilter(filter2) {
9959
- const query = this.mongooseModel.countDocuments((0, import_utils26.cloneDeep)(filter2));
9960
- return query.cast(this.mongooseModel);
9961
- }
9962
- // see https://mongoosejs.com/docs/api.html#model_Model.distinct
9963
- distinct(field, conditions = {}) {
9964
- return this.mongooseModel.distinct(field, conditions);
9965
- }
9966
- aggregate(pipeline) {
9967
- return this.mongooseModel.aggregate(pipeline);
9968
- }
9969
- };
9970
- var model_default = Model;
9971
-
9972
10256
  // src/acl/distinct-field-authorization.ts
9973
10257
  var import_utils27 = require("@web-ts-toolkit/utils");
9974
10258
  init_field_authorization();
@@ -10106,6 +10390,7 @@ init_finalize_model_output();
10106
10390
  init_populate_target();
10107
10391
  init_virtual_populate_execution();
10108
10392
  init_request_work();
10393
+ init_populate_policy2();
10109
10394
  var populateExecutors = /* @__PURE__ */ new WeakMap();
10110
10395
  function registerSubdocumentPopulateExecutor(service, execute2, core) {
10111
10396
  populateExecutors.set(service, { execute: execute2, core });
@@ -10138,7 +10423,7 @@ function prepareSubdocumentOutput(service, sub, operation, virtualAccess, output
10138
10423
  service.getServiceModelName(),
10139
10424
  { populate },
10140
10425
  0,
10141
- configuration
10426
+ getCapturedPopulatePolicyDefaults(configuration)
10142
10427
  ),
10143
10428
  void 0,
10144
10429
  configuration,
@@ -11177,12 +11462,15 @@ var Service = class extends Base {
11177
11462
  model: this.model.mongooseModel,
11178
11463
  modelName: this.modelName
11179
11464
  }),
11180
- configuration: () => this.requestRuntime.getModelInstance(this.modelName) ? captureModelAuthorizationConfiguration(
11181
- this.requestRuntime,
11182
- this.modelName,
11183
- { ...this.options, defaults: this.defaults },
11184
- modelServiceGlobalOptions(this, this.requestRuntime)
11185
- ) : { catalog: { paths: [] }, ...this.options },
11465
+ configuration: () => {
11466
+ const populatePolicyDefaults = modelServicePopulatePolicyDefaults(this, this.requestRuntime);
11467
+ return this.requestRuntime.getModelInstance(this.modelName) ? captureModelAuthorizationConfiguration(
11468
+ this.requestRuntime,
11469
+ this.modelName,
11470
+ { ...this.options, defaults: this.defaults },
11471
+ populatePolicyDefaults
11472
+ ) : { catalog: { paths: [] }, ...this.options, populatePolicyDefaults };
11473
+ },
11186
11474
  permissions: () => this.requestCore.getPermissions?.() ?? new permission_default({}),
11187
11475
  parse: (filter2) => this.parseClientData(filter2, this.getCorrelatedExecState().scheduler),
11188
11476
  validate: (filter2, expanded) => {
@@ -11231,7 +11519,7 @@ var Service = class extends Base {
11231
11519
  });
11232
11520
  }
11233
11521
  get options() {
11234
- return modelServiceOptions(this, () => this.getModelRouterOptions(this.modelName));
11522
+ return modelServiceOptions(this, this.requestRuntime, () => this.getModelRouterOptions(this.modelName));
11235
11523
  }
11236
11524
  /**
11237
11525
  * Presentation/query defaults for this service instance; an explicit assignment
@@ -11716,14 +12004,14 @@ var Service = class extends Base {
11716
12004
  }
11717
12005
  });
11718
12006
  }
11719
- captureRelated(args, defaults) {
11720
- const globalOptions = modelServiceGlobalOptions(this, this.requestRuntime);
11721
- const effective = { populate: args?.populate ?? defaults?.populate, include: args?.include ?? defaults?.include };
12007
+ captureRelated(args, defaults2) {
12008
+ const populatePolicyDefaults = modelServicePopulatePolicyDefaults(this, this.requestRuntime);
12009
+ const effective = { populate: args?.populate ?? defaults2?.populate, include: args?.include ?? defaults2?.include };
11722
12010
  if (effective.include) {
11723
12011
  const processed = this.processInclude(effective.include);
11724
12012
  effective.include = [...processed.includes, ...processed.correlatedIncludes];
11725
12013
  }
11726
- return captureRelatedTargets(this.requestRuntime, this.modelName, effective, 0, globalOptions);
12014
+ return captureRelatedTargets(this.requestRuntime, this.modelName, effective, 0, populatePolicyDefaults);
11727
12015
  }
11728
12016
  /** Canonical population uses the target's retained policy for both fetch and output. */
11729
12017
  async genExecutionPopulate(execution, access, populate) {
@@ -11749,7 +12037,12 @@ var Service = class extends Base {
11749
12037
  const modelName = target?.modelName;
11750
12038
  if (!modelName) continue;
11751
12039
  const policy = relatedPolicy(state.authorization, state.binding, descriptor.path);
11752
- const svc = this.requestCore.getPublicService(modelName);
12040
+ const svc = withCapturedPopulateModel(
12041
+ this.requestRuntime,
12042
+ modelName,
12043
+ target.model,
12044
+ () => this.requestCore.getPublicService(modelName)
12045
+ );
11753
12046
  const child = createRelatedExecution(
11754
12047
  svc,
11755
12048
  {
@@ -11794,8 +12087,8 @@ var Service = class extends Base {
11794
12087
  snapshot: readServiceAuthorization(childState.authorization, childState.binding).configuration,
11795
12088
  fetchBinding: {
11796
12089
  runtime: this.requestRuntime,
11797
- model: childState.binding.model,
11798
- schema: childState.binding.model.schema,
12090
+ model: target.model,
12091
+ schema: target.model.schema,
11799
12092
  configuration: targetConfiguration,
11800
12093
  requestRead: targetAccess === "read" && policy?.operation.mode !== "grant" && readServiceAuthorization(childState.authorization, childState.binding).authorization.rows.mode === "request",
11801
12094
  staticObjectIdReference: captured.relatedTargets.find((target2) => target2.path === descriptor.path)?.staticObjectIdReference
@@ -14652,9 +14945,20 @@ var Core = class {
14652
14945
  if (!(0, import_utils40.isString)(p)) assertPopulateAccess(p.access);
14653
14946
  }
14654
14947
  const runtime = this.requestRuntime;
14655
- const globalOptions = modelServiceGlobalOptions(this, runtime);
14656
- const relatedTargets = captureRelatedTargets(runtime, modelName, { populate: descriptors }, 0, globalOptions);
14657
- const sourceConfiguration = captureModelAuthorizationConfiguration(runtime, modelName, void 0, globalOptions);
14948
+ const populatePolicyDefaults = modelServicePopulatePolicyDefaults(this, runtime);
14949
+ const relatedTargets = captureRelatedTargets(
14950
+ runtime,
14951
+ modelName,
14952
+ { populate: descriptors },
14953
+ 0,
14954
+ populatePolicyDefaults
14955
+ );
14956
+ const sourceConfiguration = captureModelAuthorizationConfiguration(
14957
+ runtime,
14958
+ modelName,
14959
+ void 0,
14960
+ populatePolicyDefaults
14961
+ );
14658
14962
  const originalPermissions = this.getGlobalPermissions();
14659
14963
  const permissions = new permission_default(
14660
14964
  Object.fromEntries(originalPermissions.keys.map((key) => [key, originalPermissions.has(key)]))
@@ -14751,7 +15055,15 @@ var Core = class {
14751
15055
  docPermissionsAccess: planAccess,
14752
15056
  requestedSelect: originalSelect,
14753
15057
  plan: targetPlan,
14754
- snapshot: targetSnapshot
15058
+ snapshot: targetSnapshot,
15059
+ fetchBinding: {
15060
+ runtime,
15061
+ model: target.model,
15062
+ schema: target.model.schema,
15063
+ configuration: targetConfiguration,
15064
+ requestRead: populateAccess === "read",
15065
+ staticObjectIdReference: target.staticObjectIdReference
15066
+ }
14755
15067
  });
14756
15068
  return ret;
14757
15069
  })