@web-ts-toolkit/access-router 0.61.0 → 0.63.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({
@@ -598,12 +634,9 @@ var init_document = __esm({
598
634
  const out = {};
599
635
  seen.set(value, out);
600
636
  for (const [key, entry] of Object.entries(value)) {
601
- Object.defineProperty(out, key, {
602
- value: deepIsolateValue(entry, seen, flattenMaps),
603
- enumerable: true,
604
- writable: true,
605
- configurable: true
606
- });
637
+ const copied = deepIsolateValue(entry, seen, flattenMaps);
638
+ if (Object.getPrototypeOf(out) === Object.prototype && !(key in out)) out[key] = copied;
639
+ else Object.defineProperty(out, key, { value: copied, enumerable: true, writable: true, configurable: true });
607
640
  }
608
641
  copyPermissionsAlias(value, out);
609
642
  return out;
@@ -1335,7 +1368,7 @@ var init_logger_default = __esm({
1335
1368
  });
1336
1369
 
1337
1370
  // src/options/manager.ts
1338
- var import_utils11, toPath, cloneConfigValue, cloneForRead, freezeConfigValue, cloneAndFreezeForStore, getNestedOption, resolveNestedOption, OptionsManager;
1371
+ var import_utils11, toPath, cloneConfigValue, cloneForRead, freezeConfigValue, cloneAndFreezeForStore, cloneOptionsSnapshot, getNestedOption, resolveNestedOption, OptionsManager;
1339
1372
  var init_manager = __esm({
1340
1373
  "src/options/manager.ts"() {
1341
1374
  import_utils11 = require("@web-ts-toolkit/utils");
@@ -1399,6 +1432,7 @@ var init_manager = __esm({
1399
1432
  return value;
1400
1433
  };
1401
1434
  cloneAndFreezeForStore = (value) => freezeConfigValue(cloneForRead(value));
1435
+ cloneOptionsSnapshot = (value) => freezeConfigValue(cloneForRead(value));
1402
1436
  getNestedOption = (manager, key, defaultValue) => resolveNestedOption((path, fallback) => manager.get(path, fallback), String(key), defaultValue);
1403
1437
  resolveNestedOption = (read, key, defaultValue) => {
1404
1438
  const keys2 = key.split(".");
@@ -1955,6 +1989,7 @@ function copyAuthorizationValue(value, configuration = false) {
1955
1989
  if (array && input.length > 2e4) authorizationError("snapshot array exceeds structural limits");
1956
1990
  if (!array) authorizationRecord(input, "snapshot");
1957
1991
  const result2 = array ? [] : {};
1992
+ let definedProperty = false;
1958
1993
  for (const key of Reflect.ownKeys(input)) {
1959
1994
  if (array && key === "length") continue;
1960
1995
  if (typeof key !== "string" || unsafeKeys.has(key)) authorizationError("unsafe snapshot key");
@@ -1962,12 +1997,16 @@ function copyAuthorizationValue(value, configuration = false) {
1962
1997
  const descriptor = Object.getOwnPropertyDescriptor(input, key);
1963
1998
  if (!("value" in descriptor) || !descriptor.enumerable && configuration !== "document")
1964
1999
  authorizationError("accessor/non-enumerable input");
1965
- Object.defineProperty(result2, key, {
1966
- value: copy(descriptor.value, depth + 1),
1967
- enumerable: true,
1968
- writable: true,
1969
- configurable: true
1970
- });
2000
+ const value2 = copy(descriptor.value, depth + 1);
2001
+ if (array || definedProperty && Object.getPrototypeOf(result2) !== Object.prototype || key in result2) {
2002
+ definedProperty = true;
2003
+ Object.defineProperty(result2, key, {
2004
+ value: value2,
2005
+ enumerable: true,
2006
+ writable: true,
2007
+ configurable: true
2008
+ });
2009
+ } else result2[key] = value2;
1971
2010
  }
1972
2011
  if (array) result2.length = input.length;
1973
2012
  return Object.freeze(result2);
@@ -2007,10 +2046,76 @@ function outputIdentities(value) {
2007
2046
  visit(value);
2008
2047
  return Object.freeze(result2);
2009
2048
  }
2010
- var import_node_util3, import_mongoose3, import_express_json_router3, ServiceAuthorizationError, unsafeKeys;
2049
+ function tryOutputIdentitiesWithoutSnapshot(value) {
2050
+ const identities = [];
2051
+ const seen = /* @__PURE__ */ new WeakSet();
2052
+ const active = /* @__PURE__ */ new WeakSet();
2053
+ const fallback = {};
2054
+ let nodes = 0;
2055
+ function visit(input, depth) {
2056
+ if (++nodes > 2e4 || depth > 100) authorizationError("snapshot exceeds structural limits");
2057
+ if (typeof input === "function") authorizationError("functions are not policy values");
2058
+ if (typeof input === "symbol") authorizationError("symbols are not policy values");
2059
+ if (input === null || typeof input !== "object") return;
2060
+ if (import_node_util3.types.isProxy(input)) throw fallback;
2061
+ if (active.has(input)) authorizationError("cyclic input");
2062
+ if (!seen.has(input)) {
2063
+ seen.add(input);
2064
+ identities.push(input);
2065
+ }
2066
+ const prototype = Object.getPrototypeOf(input);
2067
+ if (import_node_util3.types.isDate(input)) {
2068
+ if (prototype === Date.prototype) return;
2069
+ throw fallback;
2070
+ }
2071
+ if (import_node_util3.types.isRegExp(input)) {
2072
+ if (prototype === RegExp.prototype) return;
2073
+ throw fallback;
2074
+ }
2075
+ if (import_node_util3.types.isUint8Array(input)) {
2076
+ if (prototype === import_node_buffer.Buffer.prototype) return;
2077
+ throw fallback;
2078
+ }
2079
+ if (import_node_util3.types.isMap(input) || import_node_util3.types.isSet(input)) throw fallback;
2080
+ const array = Array.isArray(input);
2081
+ if (!array) {
2082
+ if (prototype !== Object.prototype && prototype !== null) {
2083
+ let parent = prototype;
2084
+ for (let count = 0; parent && count < 100; count++) {
2085
+ if (import_node_util3.types.isProxy(parent)) throw fallback;
2086
+ if (parent === import_mongoose3.mongo.BSON.BSONValue.prototype) return;
2087
+ parent = Object.getPrototypeOf(parent);
2088
+ }
2089
+ throw fallback;
2090
+ }
2091
+ } else if (input.length > 2e4) authorizationError("snapshot array exceeds structural limits");
2092
+ active.add(input);
2093
+ try {
2094
+ for (const key of Reflect.ownKeys(input)) {
2095
+ if (array && key === "length") continue;
2096
+ if (typeof key !== "string" || unsafeKeys.has(key)) authorizationError("unsafe snapshot key");
2097
+ if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid array property");
2098
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
2099
+ if (!("value" in descriptor)) authorizationError("accessor/non-enumerable input");
2100
+ visit(descriptor.value, depth + 1);
2101
+ }
2102
+ } finally {
2103
+ active.delete(input);
2104
+ }
2105
+ }
2106
+ try {
2107
+ visit(value, 0);
2108
+ return Object.freeze(identities);
2109
+ } catch (error2) {
2110
+ if (error2 !== fallback) throw error2;
2111
+ return void 0;
2112
+ }
2113
+ }
2114
+ var import_node_util3, import_node_buffer, import_mongoose3, import_express_json_router3, ServiceAuthorizationError, unsafeKeys;
2011
2115
  var init_authorization_snapshot = __esm({
2012
2116
  "src/acl/authorization-snapshot.ts"() {
2013
2117
  import_node_util3 = require("util");
2118
+ import_node_buffer = require("buffer");
2014
2119
  import_mongoose3 = require("mongoose");
2015
2120
  import_express_json_router3 = __toESM(require("@web-ts-toolkit/express-json-router"));
2016
2121
  ServiceAuthorizationError = class extends import_express_json_router3.default.clientErrors.BadRequestError {
@@ -2025,6 +2130,29 @@ var init_authorization_snapshot = __esm({
2025
2130
  });
2026
2131
 
2027
2132
  // src/acl/field-catalog.ts
2133
+ function prepareCapturedOutputCatalog(catalog) {
2134
+ preparedOutputCatalogs.set(catalog, 0);
2135
+ }
2136
+ function prepareOutputCatalog(catalog) {
2137
+ if (import_node_util4.types.isProxy(catalog) || Object.getPrototypeOf(catalog) !== Object.prototype || !Object.isFrozen(catalog))
2138
+ return false;
2139
+ const paths = /* @__PURE__ */ new Set();
2140
+ for (const key of ["paths", "protectedPaths", "referencePaths", "virtualPaths", "dynamicPaths", "opaquePaths"]) {
2141
+ const slot = Object.getOwnPropertyDescriptor(catalog, key);
2142
+ if (!slot || !("value" in slot)) return false;
2143
+ const entries = slot.value;
2144
+ if (!Array.isArray(entries) || import_node_util4.types.isProxy(entries) || Object.getPrototypeOf(entries) !== Array.prototype || !Object.isFrozen(entries))
2145
+ return false;
2146
+ const length = Object.getOwnPropertyDescriptor(entries, "length").value;
2147
+ if (length > 2e4 || Reflect.ownKeys(entries).length !== length + 1) return false;
2148
+ for (let index = 0; index < length; index++) {
2149
+ const entry = Object.getOwnPropertyDescriptor(entries, String(index));
2150
+ if (!entry || !("value" in entry) || typeof entry.value !== "string") return false;
2151
+ if (key === "paths") paths.add(entry.value);
2152
+ }
2153
+ }
2154
+ return { paths, results: /* @__PURE__ */ new Map() };
2155
+ }
2028
2156
  function isSafeInputPath(path, requestIdentity = false) {
2029
2157
  return isSafeOutputPath(path) && path.split(".").every((part) => !inputControlSegments.has(part) && (requestIdentity || part !== "_id"));
2030
2158
  }
@@ -2047,18 +2175,35 @@ function isInputVirtualPath(catalog, path) {
2047
2175
  return false;
2048
2176
  }
2049
2177
  function matchesCatalogPattern(pattern, path, descendants = false) {
2178
+ if (typeof pattern === "string" && typeof path === "string" && !pattern.includes("$*")) {
2179
+ return pattern === path || !!descendants && path.startsWith(pattern) && path[pattern.length] === ".";
2180
+ }
2050
2181
  const expected = pattern.split(".");
2051
2182
  const actual = path.split(".");
2052
2183
  return (descendants ? actual.length >= expected.length : actual.length === expected.length) && expected.every((part, index) => part === "$*" || part === actual[index]);
2053
2184
  }
2054
2185
  function isCatalogOutputPath(catalog, path) {
2186
+ let prepared = typeof path === "string" ? preparedOutputCatalogs.get(catalog) : void 0;
2187
+ if (typeof prepared === "number") {
2188
+ const lookups = prepared + 1;
2189
+ prepared = lookups < 32 ? lookups : prepareOutputCatalog(catalog);
2190
+ preparedOutputCatalogs.set(catalog, prepared);
2191
+ if (typeof prepared === "number") return catalogOutputPath(catalog, path);
2192
+ }
2193
+ const cached = prepared ? prepared.results.get(path) : void 0;
2194
+ if (cached !== void 0) return cached;
2195
+ const allowed = catalogOutputPath(catalog, path, prepared ? prepared.paths : void 0);
2196
+ if (prepared && prepared.results.size < 2e4) prepared.results.set(path, allowed);
2197
+ return allowed;
2198
+ }
2199
+ function catalogOutputPath(catalog, path, paths) {
2055
2200
  if (!isSafeOutputPath(path)) return false;
2056
2201
  if (catalog.protectedPaths?.some((p) => matchesCatalogPattern(p, path, true))) return false;
2057
2202
  if (catalog.referencePaths?.some((p) => matchesCatalogPattern(p, path, true) && !matchesCatalogPattern(p, path)))
2058
2203
  return false;
2059
2204
  if (catalog.virtualPaths?.some((p) => matchesCatalogPattern(p, path, true) && !matchesCatalogPattern(p, path)))
2060
2205
  return false;
2061
- return catalog.paths.includes(path) || !!catalog.dynamicPaths?.some((p) => matchesCatalogPattern(p, path)) || !!catalog.opaquePaths?.some((p) => matchesCatalogPattern(p, path, true));
2206
+ return (paths ? paths.has(path) : catalog.paths.includes(path)) || !!catalog.dynamicPaths?.some((p) => matchesCatalogPattern(p, path)) || !!catalog.opaquePaths?.some((p) => matchesCatalogPattern(p, path, true));
2062
2207
  }
2063
2208
  function captureAuthorizationFieldCatalog(schema, virtuals, documentPermissionField = "_permissions") {
2064
2209
  const paths = /* @__PURE__ */ new Set();
@@ -2153,9 +2298,11 @@ function captureAuthorizationFieldCatalog(schema, virtuals, documentPermissionFi
2153
2298
  protectedPaths: Object.freeze([...protectedPaths])
2154
2299
  });
2155
2300
  }
2156
- var safeSegment, isSafeOutputPath, inputControlSegments;
2301
+ var import_node_util4, preparedOutputCatalogs, safeSegment, isSafeOutputPath, inputControlSegments;
2157
2302
  var init_field_catalog = __esm({
2158
2303
  "src/acl/field-catalog.ts"() {
2304
+ import_node_util4 = require("util");
2305
+ preparedOutputCatalogs = /* @__PURE__ */ new WeakMap();
2159
2306
  safeSegment = (part) => !!part && part !== "sub" && !["__proto__", "constructor", "prototype", "_doc", "__v"].includes(part) && !/^[+$-]|[\s*]/.test(part) && !part.includes("[") && !part.includes("]") && !/^\d+$/.test(part) && ![...part].some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127);
2160
2307
  isSafeOutputPath = (path) => path.split(".").every(safeSegment);
2161
2308
  inputControlSegments = /* @__PURE__ */ new Set([
@@ -2179,8 +2326,45 @@ var init_field_catalog = __esm({
2179
2326
  }
2180
2327
  });
2181
2328
 
2329
+ // src/runtime-context.ts
2330
+ function runWithRuntime(runtime, callback) {
2331
+ return runtimeStorage.run(runtime, callback);
2332
+ }
2333
+ function getActiveRuntime() {
2334
+ return runtimeStorage.getStore() ?? null;
2335
+ }
2336
+ var import_node_async_hooks2, runtimeStorage;
2337
+ var init_runtime_context = __esm({
2338
+ "src/runtime-context.ts"() {
2339
+ import_node_async_hooks2 = require("async_hooks");
2340
+ runtimeStorage = new import_node_async_hooks2.AsyncLocalStorage();
2341
+ }
2342
+ });
2343
+
2344
+ // src/meta.ts
2345
+ var getRuntime, getModelReference;
2346
+ var init_meta = __esm({
2347
+ "src/meta.ts"() {
2348
+ init_runtime();
2349
+ init_runtime_context();
2350
+ getRuntime = () => getActiveRuntime() ?? defaultRuntime;
2351
+ getModelReference = (modelName, refPath, runtime = getRuntime()) => {
2352
+ const instance = runtime.getModelInstance(modelName);
2353
+ let type = instance?.schema.path(refPath);
2354
+ const result2 = {};
2355
+ while (type) {
2356
+ result2.ref ??= type.options?.ref;
2357
+ result2.refPath ??= type.options?.refPath;
2358
+ if (type.instance !== "Array") break;
2359
+ type = type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
2360
+ }
2361
+ return result2;
2362
+ };
2363
+ }
2364
+ });
2365
+
2182
2366
  // src/acl/populate-target-configuration.ts
2183
- function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions) {
2367
+ function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions, defaults2 = runtime.getDefaultModelOptions()) {
2184
2368
  const label = `Populate target "${modelName}" for ${source}`;
2185
2369
  if (!proposedOptions && !runtime.hasModel(modelName))
2186
2370
  authorizationError(
@@ -2189,18 +2373,77 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
2189
2373
  const model = runtime.getModelInstance(modelName);
2190
2374
  if (!model) authorizationError(`${label} requires an actual registered Mongoose model in this runtime`);
2191
2375
  const options = proposedOptions ?? runtime.getModelOptions(modelName);
2192
- const permissionSchema = options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema;
2376
+ const permissionSchema = options.permissionSchema === void 0 ? defaults2.permissionSchema : options.permissionSchema;
2193
2377
  if (!(0, import_utils15.isPlainObject)(permissionSchema))
2194
2378
  authorizationError(
2195
2379
  `${label} requires an effective object permissionSchema; configure the model or runtime model defaults ({} explicitly closes business fields)`
2196
2380
  );
2197
2381
  return { model, options: { ...options, permissionSchema } };
2198
2382
  }
2383
+ function capturePopulateTargetBinding(runtime, sourceModelName, path) {
2384
+ const { ref, refPath } = getModelReference(sourceModelName, path, runtime);
2385
+ if (refPath !== void 0 || typeof ref === "function" && !("modelName" in ref))
2386
+ authorizationError(
2387
+ `Populate target for ${sourceModelName}.${path} requires a static string or Mongoose Model-valued source ref; dynamic refs/refPath cannot be bound before I/O`
2388
+ );
2389
+ const modelName = typeof ref === "string" ? ref : ref?.modelName;
2390
+ if (!modelName) return void 0;
2391
+ const target = capturePopulateTargetConfiguration(runtime, modelName, `${sourceModelName}.${path}`);
2392
+ const source = runtime.getModelInstance(sourceModelName);
2393
+ const actual = typeof ref === "string" ? source?.db.models[ref] : ref;
2394
+ if (!actual)
2395
+ authorizationError(
2396
+ `Populate target "${modelName}" for ${sourceModelName}.${path} is missing on the source connection; configure the actual model bound to the source ref in this runtime`
2397
+ );
2398
+ if (actual !== target.model)
2399
+ authorizationError(
2400
+ `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`
2401
+ );
2402
+ return { ...target, modelName };
2403
+ }
2199
2404
  var import_utils15;
2200
2405
  var init_populate_target_configuration = __esm({
2201
2406
  "src/acl/populate-target-configuration.ts"() {
2202
2407
  import_utils15 = require("@web-ts-toolkit/utils");
2203
2408
  init_authorization_snapshot();
2409
+ init_meta();
2410
+ }
2411
+ });
2412
+
2413
+ // src/acl/populate-policy.ts
2414
+ function capturePopulatePolicyDefaults(runtime) {
2415
+ const options = runtime.getDefaultModelOptions();
2416
+ const token = () => {
2417
+ };
2418
+ defaults.set(
2419
+ token,
2420
+ Object.freeze({
2421
+ requireOperationAccessForPopulateQueries: options.requireOperationAccessForPopulateQueries !== false,
2422
+ requireOperationAccessForPopulateDependencies: options.requireOperationAccessForPopulateDependencies !== false
2423
+ })
2424
+ );
2425
+ return token;
2426
+ }
2427
+ function resolvePopulatePolicy(options, token) {
2428
+ const captured = defaults.get(token);
2429
+ if (!captured) return authorizationError("invalid captured populate model defaults");
2430
+ const resolve = (key) => (options[key] === void 0 ? captured[key] : options[key]) !== false;
2431
+ return Object.freeze({
2432
+ requireOperationAccessForPopulateQueries: resolve(populatePolicyKeys[0]),
2433
+ requireOperationAccessForPopulateDependencies: resolve(populatePolicyKeys[1])
2434
+ });
2435
+ }
2436
+ function getCapturedPopulatePolicyDefaults(configuration) {
2437
+ const token = configuration.populatePolicyDefaults;
2438
+ if (!token || !defaults.has(token)) return authorizationError("missing captured populate model defaults");
2439
+ return token;
2440
+ }
2441
+ var defaults;
2442
+ var init_populate_policy2 = __esm({
2443
+ "src/acl/populate-policy.ts"() {
2444
+ init_populate_policy();
2445
+ init_authorization_snapshot();
2446
+ defaults = /* @__PURE__ */ new WeakMap();
2204
2447
  }
2205
2448
  });
2206
2449
 
@@ -2294,9 +2537,7 @@ function normalizeSelection(select, catalog, label) {
2294
2537
  includeId: selection.includes("_id")
2295
2538
  };
2296
2539
  }
2297
- function captureVirtualPopulateDependencies(runtime, modelName, options, globalOptions = runtime.getGlobalOptions()) {
2298
- const requireOperationAccessForPopulateDependencies = globalOptions.requireOperationAccessForPopulateDependencies !== false;
2299
- const requireOperationAccessForPopulateQueries = globalOptions.requireOperationAccessForPopulateQueries !== false;
2540
+ function captureVirtualPopulateDependencies(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime), proposed) {
2300
2541
  const model = runtime.getModelInstance(modelName);
2301
2542
  const targets = /* @__PURE__ */ new Map();
2302
2543
  const scopes = [];
@@ -2340,18 +2581,19 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, globalO
2340
2581
  runtime,
2341
2582
  ref,
2342
2583
  `dependsOnPopulate virtual "${label}"`,
2343
- ref === modelName ? options : void 0
2584
+ ref === modelName ? options : proposed?.models.get(ref),
2585
+ proposed?.defaults
2344
2586
  );
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;
2587
+ const defaults2 = proposed?.defaults ?? runtime.getDefaultModelOptions();
2588
+ const readOption = (key) => resolveNestedOption((path2, fallback) => (0, import_utils16.get)(targetOptions, path2, fallback), key, (0, import_utils16.get)(defaults2, key));
2589
+ const documentPermissionField = targetOptions.documentPermissionField ?? defaults2.documentPermissionField;
2348
2590
  const catalog = captureAuthorizationFieldCatalog(targetModel.schema, void 0, documentPermissionField);
2349
2591
  const configuration = copyAuthorizationValue(
2350
2592
  {
2351
2593
  catalog,
2352
2594
  documentPermissionField,
2353
- requireOperationAccessForPopulateDependencies,
2354
- requireOperationAccessForPopulateQueries,
2595
+ populatePolicyDefaults,
2596
+ ...resolvePopulatePolicy(targetOptions, populatePolicyDefaults),
2355
2597
  permissionSchema: targetOptions.permissionSchema,
2356
2598
  operationAccess: { read: readOption("operationAccess.read") },
2357
2599
  baseFilter: { read: readOption("baseFilter.read") },
@@ -2432,8 +2674,8 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, globalO
2432
2674
  visit(options.virtuals ?? {}, model?.schema, "", [], !!model && varyingModel(model));
2433
2675
  return Object.freeze({ scopes: Object.freeze(scopes) });
2434
2676
  }
2435
- function captureVirtualPopulateSnapshot(runtime, modelName, options, globalOptions = runtime.getGlobalOptions()) {
2436
- const snapshot = captureVirtualPopulateDependencies(runtime, modelName, options, globalOptions);
2677
+ function captureVirtualPopulateSnapshot(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime)) {
2678
+ const snapshot = captureVirtualPopulateDependencies(runtime, modelName, options, populatePolicyDefaults);
2437
2679
  const token = () => {
2438
2680
  };
2439
2681
  snapshots.set(token, snapshot);
@@ -2467,6 +2709,7 @@ var init_virtual_populate_dependencies = __esm({
2467
2709
  init_field_catalog();
2468
2710
  init_virtual_descriptor();
2469
2711
  init_populate_target_configuration();
2712
+ init_populate_policy2();
2470
2713
  elementType = (type) => type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
2471
2714
  join = (prefix, path) => prefix ? `${prefix}.${path}` : path;
2472
2715
  within = (path, parent) => path === parent || path.startsWith(`${parent}.`);
@@ -2481,12 +2724,13 @@ var init_virtual_populate_dependencies = __esm({
2481
2724
  });
2482
2725
 
2483
2726
  // 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;
2727
+ 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
2728
  var init_runtime = __esm({
2486
2729
  "src/runtime.ts"() {
2487
2730
  import_mongoose4 = __toESM(require("mongoose"));
2488
2731
  init_public_admission();
2489
2732
  init_hydration();
2733
+ init_populate_policy();
2490
2734
  import_mongoose_schema_jsonschema = __toESM(require("mongoose-schema-jsonschema"));
2491
2735
  import_utils17 = require("@web-ts-toolkit/utils");
2492
2736
  init_helpers();
@@ -2498,6 +2742,7 @@ var init_runtime = __esm({
2498
2742
  init_request_complexity();
2499
2743
  init_virtual_descriptor();
2500
2744
  init_virtual_populate_dependencies();
2745
+ init_unsafe_snapshot_options();
2501
2746
  mongooseJsonSchemaInitialized = false;
2502
2747
  ensureMongooseJsonSchemaInitialized = () => {
2503
2748
  if (mongooseJsonSchemaInitialized) return;
@@ -2510,6 +2755,15 @@ var init_runtime = __esm({
2510
2755
  basePath: null,
2511
2756
  alwaysSelectFields: []
2512
2757
  };
2758
+ modelOverrides = (options) => {
2759
+ const result2 = Object.fromEntries(
2760
+ Object.entries(options).filter(
2761
+ ([key, value]) => value !== void 0 || key === "operationAccess" || isPopulatePolicyKey(key)
2762
+ )
2763
+ );
2764
+ for (const key of unsafeSnapshotOptions) if (key in result2) result2[key] = result2[key] === true;
2765
+ return cloneOptionsSnapshot(result2);
2766
+ };
2513
2767
  defaultDataOptions = {
2514
2768
  basePath: null,
2515
2769
  parentPath: "/",
@@ -2643,12 +2897,12 @@ var init_runtime = __esm({
2643
2897
  }
2644
2898
  return fields;
2645
2899
  };
2646
- cloneVirtualsForValidation = (value) => {
2647
- if (Array.isArray(value)) return value.map((item) => cloneVirtualsForValidation(item));
2900
+ cloneModelOptionForUpdate = (value) => {
2901
+ if (Array.isArray(value)) return value.map((item) => cloneModelOptionForUpdate(item));
2648
2902
  if (!value || typeof value !== "object") return value;
2649
2903
  if (Object.getPrototypeOf(value) !== Object.prototype) return value;
2650
2904
  return Object.fromEntries(
2651
- Object.entries(value).map(([k, v]) => [k, cloneVirtualsForValidation(v)])
2905
+ Object.entries(value).map(([k, v]) => [k, cloneModelOptionForUpdate(v)])
2652
2906
  );
2653
2907
  };
2654
2908
  validateVirtualDependsOn = (dependsOn, entryLabel, storedFields, siblingVirtualNames) => {
@@ -2844,8 +3098,6 @@ var init_runtime = __esm({
2844
3098
  {
2845
3099
  requestPermissionField: "_permissions",
2846
3100
  globalPermissions: () => ({}),
2847
- requireOperationAccessForPopulateQueries: true,
2848
- requireOperationAccessForPopulateDependencies: true,
2849
3101
  logger: defaultLogger,
2850
3102
  requestComplexity: defaultRequestComplexity
2851
3103
  },
@@ -2860,15 +3112,20 @@ var init_runtime = __esm({
2860
3112
  queryRouteSegment: "__query",
2861
3113
  mutationRouteSegment: "__mutation",
2862
3114
  operationAccess: false,
3115
+ requireOperationAccessForPopulateQueries: true,
3116
+ requireOperationAccessForPopulateDependencies: true,
2863
3117
  modelPermissionPrefix: "",
2864
3118
  unsafeSkipListDocumentSnapshotChecks: false,
2865
3119
  unsafeSkipReadDocumentSnapshotChecks: false,
2866
3120
  unsafeSkipListOutputSnapshotChecks: false,
2867
3121
  unsafeSkipReadOutputSnapshotChecks: false,
2868
3122
  unsafeSkipListNestedDocumentSnapshotChecks: false,
2869
- unsafeSkipReadNestedDocumentSnapshotChecks: false
3123
+ unsafeSkipReadNestedDocumentSnapshotChecks: false,
3124
+ unsafeSkipListInitialOutputSnapshotCopy: false,
3125
+ unsafeSkipReadInitialOutputSnapshotCopy: false
2870
3126
  }).build();
2871
3127
  this.modelOptions = {};
3128
+ this.modelOptionOverrides = {};
2872
3129
  this.modelJsonSchemas = {};
2873
3130
  this.dataOptions = {};
2874
3131
  this.modelRefs = {};
@@ -2956,6 +3213,7 @@ var init_runtime = __esm({
2956
3213
  globalOptions: this.globalOptions.snapshot(),
2957
3214
  defaultModelOptions: this.defaultModelOptions.snapshot(),
2958
3215
  modelOptions: modelOptionsSnap,
3216
+ modelOptionOverrides: { ...this.modelOptionOverrides },
2959
3217
  dataOptions: dataOptionsSnap,
2960
3218
  modelInstances: { ...this.modelInstances },
2961
3219
  modelJsonSchemas: { ...this.modelJsonSchemas },
@@ -2970,6 +3228,10 @@ var init_runtime = __esm({
2970
3228
  restoreBootstrapSnapshot(snapshot) {
2971
3229
  this.globalOptions.restore(snapshot.globalOptions);
2972
3230
  this.defaultModelOptions.restore(snapshot.defaultModelOptions);
3231
+ for (const name of Object.keys(this.modelOptionOverrides)) delete this.modelOptionOverrides[name];
3232
+ for (const [name, options] of Object.entries(snapshot.modelOptionOverrides)) {
3233
+ this.modelOptionOverrides[name] = modelOverrides(options);
3234
+ }
2973
3235
  for (const name of Object.keys(this.modelOptions)) {
2974
3236
  if (!(name in snapshot.modelOptions)) {
2975
3237
  delete this.modelOptions[name];
@@ -2980,8 +3242,7 @@ var init_runtime = __esm({
2980
3242
  if (existing) {
2981
3243
  existing.restore(opts);
2982
3244
  } else {
2983
- const mgr = this.createModelOptions(name);
2984
- mgr.restore(opts);
3245
+ const mgr = this.createModelOptions(name, opts);
2985
3246
  this.modelOptions[name] = mgr;
2986
3247
  }
2987
3248
  }
@@ -3024,18 +3285,11 @@ var init_runtime = __esm({
3024
3285
  }
3025
3286
  /** Shallowly replace supplied global values; nested objects such as requestComplexity are not deep-merged. */
3026
3287
  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);
3288
+ for (const key of populatePolicyKeys) if (key in options) assertNoGlobalPopulatePolicy(key);
3289
+ this.globalOptions.assign({ ...options });
3033
3290
  }
3034
3291
  setGlobalOption(key, value) {
3035
- if (key === "requireOperationAccessForPopulateQueries" || key === "requireOperationAccessForPopulateDependencies") {
3036
- this.globalOptions.set(key, value !== false);
3037
- return;
3038
- }
3292
+ assertNoGlobalPopulatePolicy(String(key));
3039
3293
  this.globalOptions.set(key, value);
3040
3294
  }
3041
3295
  getGlobalOptions() {
@@ -3044,28 +3298,30 @@ var init_runtime = __esm({
3044
3298
  getGlobalOption(key, defaultValue) {
3045
3299
  return this.globalOptions.get(key, defaultValue);
3046
3300
  }
3047
- /** Update model starting defaults shallowly; already-stored model values are not broadcast-replaced. */
3301
+ /** Update inherited model defaults shallowly. Explicit model values and captured calls are unchanged. */
3048
3302
  setDefaultModelOptions(options) {
3049
3303
  assertPublicDefaults(options.defaults);
3050
3304
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
3051
- this.defaultModelOptions.assign(options);
3305
+ const draft = new OptionsManager(
3306
+ this.getDefaultModelOptions()
3307
+ ).build();
3308
+ draft.assign(normalizePopulatePolicyOptions(options));
3309
+ this.publishDefaultModelOptions(draft.fetch());
3052
3310
  }
3053
3311
  setDefaultModelOption(key, value) {
3054
3312
  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);
3313
+ const draft = new OptionsManager(
3314
+ this.getDefaultModelOptions()
3315
+ ).build();
3316
+ if (isPopulatePolicyKey(keyStr)) {
3317
+ draft.set(keyStr, normalizePopulatePolicyValue(value));
3318
+ } else if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
3319
+ draft.set("hydration", normalizeHydrationUpdate(this.getDefaultModelOptions().hydration, keyStr, value));
3320
+ } else {
3321
+ draft.set(key, value);
3067
3322
  }
3068
- this.defaultModelOptions.set(key, value);
3323
+ assertPublicDefaults(draft.fetch().defaults);
3324
+ this.publishDefaultModelOptions(draft.fetch());
3069
3325
  }
3070
3326
  getDefaultModelOptions() {
3071
3327
  return this.defaultModelOptions.fetch();
@@ -3073,30 +3329,103 @@ var init_runtime = __esm({
3073
3329
  getDefaultModelOption(key, defaultValue) {
3074
3330
  return this.defaultModelOptions.get(key, defaultValue);
3075
3331
  }
3076
- createModelOptions(modelName) {
3332
+ resolveModelOptions(modelName, overrides = this.modelOptionOverrides[modelName] ?? {}, defaults2 = this.getDefaultModelOptions()) {
3333
+ const inherited = { ...defaults2 };
3334
+ for (const key of populatePolicyKeys) delete inherited[key];
3335
+ const effective = { ...defaultModelOptions, ...inherited, ...overrides, modelName };
3336
+ effective.basePath = normalizeBasePath(modelName, effective.basePath);
3337
+ for (const key of unsafeSnapshotOptions) effective[key] = effective[key] === true;
3338
+ refreshPermissionMetadata(effective);
3339
+ return cloneOptionsSnapshot(effective);
3340
+ }
3341
+ validateModelOptions(modelName, options, proposed) {
3342
+ validateVirtualsTree(
3343
+ this.getModelInstance(modelName),
3344
+ options.virtuals,
3345
+ options.documentPermissionField ?? "_permissions",
3346
+ modelName
3347
+ );
3348
+ captureVirtualPopulateDependencies(this, modelName, options, void 0, proposed);
3349
+ }
3350
+ publishDefaultModelOptions(options) {
3351
+ const next = { ...options };
3352
+ for (const key of unsafeSnapshotOptions) if (key in next) next[key] = next[key] === true;
3353
+ const defaults2 = cloneOptionsSnapshot(next);
3354
+ const models = new Map(
3355
+ Object.keys(this.modelOptions).map((name) => [name, this.resolveModelOptions(name, void 0, defaults2)])
3356
+ );
3357
+ for (const [name, options2] of models) this.validateModelOptions(name, options2, { defaults: defaults2, models });
3358
+ this.deferSnapshotWarnings(() => {
3359
+ this.defaultModelOptions.restore(defaults2);
3360
+ for (const [name, options2] of models) this.modelOptions[name].restore(options2);
3361
+ });
3362
+ }
3363
+ warnSnapshotFlag(modelName, key) {
3364
+ if (this.pendingSnapshotWarnings) {
3365
+ this.pendingSnapshotWarnings.push({ modelName, key });
3366
+ return;
3367
+ }
3368
+ const operation = key.startsWith("unsafeSkipRead") ? "read" : "list";
3369
+ const category = key.includes("NestedDocument") ? "nested-document" : key.includes("Output") ? "output" : "document";
3370
+ const risk = category === "output" ? "output mutation" : "source mutation";
3371
+ try {
3372
+ this.getGlobalOption("logger")?.warn?.(
3373
+ `UNSAFE: ${operation} ${category} snapshot checks disabled; ${risk} can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
3374
+ { modelName }
3375
+ );
3376
+ } catch {
3377
+ }
3378
+ }
3379
+ deferSnapshotWarnings(publish) {
3380
+ if (this.pendingSnapshotWarnings) return publish();
3381
+ const copyModes = this.initialOutputCopyModes();
3382
+ const pending = [];
3383
+ this.pendingSnapshotWarnings = pending;
3384
+ let result2;
3385
+ try {
3386
+ result2 = publish();
3387
+ } finally {
3388
+ this.pendingSnapshotWarnings = void 0;
3389
+ }
3390
+ const nextCopyModes = this.initialOutputCopyModes();
3391
+ for (const { modelName, key } of pending) this.warnSnapshotFlag(modelName, key);
3392
+ for (const [modelName, modes] of nextCopyModes) {
3393
+ for (const operation of ["List", "Read"]) {
3394
+ const mode = modes[operation];
3395
+ if (mode === "off" || mode === copyModes.get(modelName)?.[operation]) continue;
3396
+ const key = `unsafeSkip${operation}InitialOutputSnapshotCopy`;
3397
+ const prerequisite = `unsafeSkip${operation}OutputSnapshotChecks`;
3398
+ try {
3399
+ this.getGlobalOption("logger")?.warn?.(
3400
+ 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.`,
3401
+ { modelName }
3402
+ );
3403
+ } catch {
3404
+ }
3405
+ }
3406
+ }
3407
+ return result2;
3408
+ }
3409
+ initialOutputCopyModes() {
3410
+ return new Map(
3411
+ Object.entries(this.modelOptions).map(([modelName, options]) => {
3412
+ const mode = (operation) => options.get(`unsafeSkip${operation}InitialOutputSnapshotCopy`) !== true ? "off" : options.get(`unsafeSkip${operation}OutputSnapshotChecks`) === true ? "active" : "dormant";
3413
+ return [modelName, { List: mode("List"), Read: mode("Read") }];
3414
+ })
3415
+ );
3416
+ }
3417
+ createModelOptions(modelName, options = this.resolveModelOptions(modelName)) {
3077
3418
  const model = this.getModelInstance(modelName);
3078
3419
  if (!model) {
3079
3420
  throw new Error(
3080
3421
  `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this isolated runtime.`
3081
3422
  );
3082
3423
  }
3083
- const manager = new OptionsManager({
3084
- ...defaultModelOptions,
3085
- modelName
3086
- });
3424
+ const manager = new OptionsManager(options);
3087
3425
  const snapshotFlagChanged = (newValue, key, target, oldValue) => {
3088
3426
  target[key] = newValue === true;
3089
3427
  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
- }
3428
+ this.warnSnapshotFlag(modelName, key);
3100
3429
  };
3101
3430
  manager.onchange("permissionSchema", function(_newval, _key, target) {
3102
3431
  refreshPermissionMetadata(target);
@@ -3114,13 +3443,17 @@ var init_runtime = __esm({
3114
3443
  getOrCreateModelOptions(modelName) {
3115
3444
  let manager = this.modelOptions[modelName];
3116
3445
  if (!manager) {
3117
- manager = this.createModelOptions(modelName);
3118
- this.modelOptions[modelName] = manager;
3446
+ manager = this.deferSnapshotWarnings(() => {
3447
+ const created = this.createModelOptions(modelName);
3448
+ this.modelOptions[modelName] = created;
3449
+ return created;
3450
+ });
3119
3451
  }
3120
3452
  return manager;
3121
3453
  }
3122
3454
  /**
3123
- * Assign `{ ...modelDefaults, ...storedOptions, ...options }` shallowly. A supplied
3455
+ * Update explicit model overrides shallowly; undefined restores default inheritance
3456
+ * (operationAccess preserves its existing exact-key-only default fallback). A supplied
3124
3457
  * operationAccess/defaults object replaces that whole value. Defaults accept only
3125
3458
  * query/presentation settings; virtual configuration is validated before assignment.
3126
3459
  * Existing router.options remains its construction-time snapshot. Fresh model-service
@@ -3128,22 +3461,23 @@ var init_runtime = __esm({
3128
3461
  */
3129
3462
  setModelOptions(modelName, options) {
3130
3463
  assertPublicDefaults(options.defaults);
3464
+ options = normalizePopulatePolicyOptions(options);
3131
3465
  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 });
3466
+ const overrides = modelOverrides({ ...this.modelOptionOverrides[modelName], ...options });
3467
+ const effective = this.resolveModelOptions(modelName, overrides);
3468
+ this.validateModelOptions(modelName, effective);
3469
+ this.deferSnapshotWarnings(() => {
3470
+ const manager = this.modelOptions[modelName];
3471
+ if (manager) manager.restore(effective);
3472
+ else this.modelOptions[modelName] = this.createModelOptions(modelName, effective);
3473
+ this.modelOptionOverrides[modelName] = overrides;
3474
+ });
3141
3475
  }
3142
3476
  setModelOption(modelName, key, value) {
3143
3477
  const keyStr = String(key);
3144
3478
  if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
3145
- const hydration = normalizeHydrationUpdate(this.modelOptions[modelName]?.get("hydration"), keyStr, value);
3146
- this.getOrCreateModelOptions(modelName).set("hydration", hydration);
3479
+ const hydration = normalizeHydrationUpdate(this.resolveModelOptions(modelName).hydration, keyStr, value);
3480
+ this.setModelOptions(modelName, { hydration });
3147
3481
  return;
3148
3482
  }
3149
3483
  if (keyStr === "defaults") assertPublicDefaults(value);
@@ -3152,47 +3486,20 @@ var init_runtime = __esm({
3152
3486
  (0, import_utils17.set)(proposed, keyStr.slice("defaults.".length), value);
3153
3487
  assertPublicDefaults(proposed);
3154
3488
  }
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
- });
3489
+ const [root, ...path] = keyStr.split(".");
3490
+ if (!path.length) {
3491
+ this.setModelOptions(modelName, { [root]: value });
3492
+ return;
3192
3493
  }
3193
- this.getOrCreateModelOptions(modelName).set(key, value);
3194
- }
3195
- /** Frozen stored snapshot, not fully resolved per-path defaults. Read again for current configuration. */
3494
+ const current = this.resolveModelOptions(modelName);
3495
+ const nested = cloneModelOptionForUpdate((0, import_utils17.isPlainObject)(current[root]) ? current[root] : {});
3496
+ if (root === "virtuals" && value === void 0) {
3497
+ const parent = path.length === 1 ? nested : (0, import_utils17.get)(nested, path.slice(0, -1));
3498
+ if ((0, import_utils17.isPlainObject)(parent)) delete parent[path[path.length - 1]];
3499
+ } else (0, import_utils17.set)(nested, path, value);
3500
+ this.setModelOptions(modelName, { [root]: nested });
3501
+ }
3502
+ /** Frozen model/default snapshot; populate flags remain raw overrides. Read again for current values. */
3196
3503
  getModelOptions(modelName) {
3197
3504
  const manager = this.getOrCreateModelOptions(modelName);
3198
3505
  return manager.fetch();
@@ -3359,132 +3666,117 @@ var init_runtime = __esm({
3359
3666
  }
3360
3667
  });
3361
3668
 
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
3669
  // src/options/global-options.ts
3378
- var getRuntime, setGlobalOptions, setGlobalOption, getGlobalOptions, getGlobalOption;
3670
+ var getRuntime2, setGlobalOptions, setGlobalOption, getGlobalOptions, getGlobalOption;
3379
3671
  var init_global_options = __esm({
3380
3672
  "src/options/global-options.ts"() {
3381
3673
  init_runtime();
3382
3674
  init_runtime_context();
3383
- getRuntime = () => getActiveRuntime() ?? defaultRuntime;
3675
+ getRuntime2 = () => getActiveRuntime() ?? defaultRuntime;
3384
3676
  setGlobalOptions = (options) => {
3385
- getRuntime().setGlobalOptions(options);
3677
+ getRuntime2().setGlobalOptions(options);
3386
3678
  };
3387
3679
  setGlobalOption = (key, value) => {
3388
- getRuntime().setGlobalOption(key, value);
3680
+ getRuntime2().setGlobalOption(key, value);
3389
3681
  };
3390
3682
  getGlobalOptions = () => {
3391
- return getRuntime().getGlobalOptions();
3683
+ return getRuntime2().getGlobalOptions();
3392
3684
  };
3393
3685
  getGlobalOption = (key, defaultValue) => {
3394
- return getRuntime().getGlobalOption(key, defaultValue);
3686
+ return getRuntime2().getGlobalOption(key, defaultValue);
3395
3687
  };
3396
3688
  }
3397
3689
  });
3398
3690
 
3399
3691
  // src/options/model-options.ts
3400
- var getRuntime2, setModelOptions, setModelOption, getModelOptions, getModelOption, getExactModelOption, getModelNames, getModelJsonSchema, registerModelInstance, hasModelInstance, getModelInstance;
3692
+ var getRuntime3, setModelOptions, setModelOption, getModelOptions, getModelOption, getExactModelOption, getModelNames, getModelJsonSchema, registerModelInstance, hasModelInstance, getModelInstance;
3401
3693
  var init_model_options = __esm({
3402
3694
  "src/options/model-options.ts"() {
3403
3695
  init_runtime();
3404
3696
  init_runtime_context();
3405
- getRuntime2 = () => getActiveRuntime() ?? defaultRuntime;
3697
+ getRuntime3 = () => getActiveRuntime() ?? defaultRuntime;
3406
3698
  setModelOptions = (modelName, options) => {
3407
- getRuntime2().setModelOptions(modelName, options);
3699
+ getRuntime3().setModelOptions(modelName, options);
3408
3700
  };
3409
3701
  setModelOption = (modelName, key, value) => {
3410
- getRuntime2().setModelOption(modelName, key, value);
3702
+ getRuntime3().setModelOption(modelName, key, value);
3411
3703
  };
3412
3704
  getModelOptions = (modelName) => {
3413
- return getRuntime2().getModelOptions(modelName);
3705
+ return getRuntime3().getModelOptions(modelName);
3414
3706
  };
3415
3707
  getModelOption = (modelName, key, defaultValue) => {
3416
- return getRuntime2().getModelOption(modelName, key, defaultValue);
3708
+ return getRuntime3().getModelOption(modelName, key, defaultValue);
3417
3709
  };
3418
3710
  getExactModelOption = (modelName, key) => {
3419
- return getRuntime2().getExactModelOption(modelName, key);
3711
+ return getRuntime3().getExactModelOption(modelName, key);
3420
3712
  };
3421
3713
  getModelNames = () => {
3422
3714
  return (getActiveRuntime() ?? defaultRuntime).getModelNames();
3423
3715
  };
3424
3716
  getModelJsonSchema = (modelName) => {
3425
- return getRuntime2().getModelJsonSchema(modelName);
3717
+ return getRuntime3().getModelJsonSchema(modelName);
3426
3718
  };
3427
3719
  registerModelInstance = (modelName, model) => {
3428
- getRuntime2().registerModelInstance(modelName, model);
3720
+ getRuntime3().registerModelInstance(modelName, model);
3429
3721
  };
3430
3722
  hasModelInstance = (modelName) => {
3431
- return getRuntime2().hasModelInstance(modelName);
3723
+ return getRuntime3().hasModelInstance(modelName);
3432
3724
  };
3433
3725
  getModelInstance = (modelName) => {
3434
- return getRuntime2().getModelInstance(modelName);
3726
+ return getRuntime3().getModelInstance(modelName);
3435
3727
  };
3436
3728
  }
3437
3729
  });
3438
3730
 
3439
3731
  // src/options/default-model-options.ts
3440
- var getRuntime3, setDefaultModelOptions, setDefaultModelOption, getDefaultModelOptions, getDefaultModelOption;
3732
+ var getRuntime4, setDefaultModelOptions, setDefaultModelOption, getDefaultModelOptions, getDefaultModelOption;
3441
3733
  var init_default_model_options = __esm({
3442
3734
  "src/options/default-model-options.ts"() {
3443
3735
  init_runtime();
3444
3736
  init_runtime_context();
3445
- getRuntime3 = () => getActiveRuntime() ?? defaultRuntime;
3737
+ getRuntime4 = () => getActiveRuntime() ?? defaultRuntime;
3446
3738
  setDefaultModelOptions = (options) => {
3447
- getRuntime3().setDefaultModelOptions(options);
3739
+ getRuntime4().setDefaultModelOptions(options);
3448
3740
  };
3449
3741
  setDefaultModelOption = (key, value) => {
3450
- getRuntime3().setDefaultModelOption(key, value);
3742
+ getRuntime4().setDefaultModelOption(key, value);
3451
3743
  };
3452
3744
  getDefaultModelOptions = () => {
3453
- return getRuntime3().getDefaultModelOptions();
3745
+ return getRuntime4().getDefaultModelOptions();
3454
3746
  };
3455
3747
  getDefaultModelOption = (key, defaultValue) => {
3456
- return getRuntime3().getDefaultModelOption(key, defaultValue);
3748
+ return getRuntime4().getDefaultModelOption(key, defaultValue);
3457
3749
  };
3458
3750
  }
3459
3751
  });
3460
3752
 
3461
3753
  // src/options/data-options.ts
3462
- var getRuntime4, setDataOptions, setDataOption, getDataOptions, getDataSnapshot, getDataOption, getExactDataOption, getDataNames;
3754
+ var getRuntime5, setDataOptions, setDataOption, getDataOptions, getDataSnapshot, getDataOption, getExactDataOption, getDataNames;
3463
3755
  var init_data_options = __esm({
3464
3756
  "src/options/data-options.ts"() {
3465
3757
  init_runtime();
3466
3758
  init_runtime_context();
3467
- getRuntime4 = () => getActiveRuntime() ?? defaultRuntime;
3759
+ getRuntime5 = () => getActiveRuntime() ?? defaultRuntime;
3468
3760
  setDataOptions = (dataName, options) => {
3469
- getRuntime4().setDataOptions(dataName, options);
3761
+ getRuntime5().setDataOptions(dataName, options);
3470
3762
  };
3471
3763
  setDataOption = (dataName, key, value) => {
3472
- getRuntime4().setDataOption(dataName, key, value);
3764
+ getRuntime5().setDataOption(dataName, key, value);
3473
3765
  };
3474
3766
  getDataOptions = (dataName) => {
3475
- return getRuntime4().getDataOptions(dataName);
3767
+ return getRuntime5().getDataOptions(dataName);
3476
3768
  };
3477
3769
  getDataSnapshot = (dataName) => {
3478
- return getRuntime4().getDataSnapshot(dataName);
3770
+ return getRuntime5().getDataSnapshot(dataName);
3479
3771
  };
3480
3772
  getDataOption = (dataName, key, defaultValue) => {
3481
- return getRuntime4().getDataOption(dataName, key, defaultValue);
3773
+ return getRuntime5().getDataOption(dataName, key, defaultValue);
3482
3774
  };
3483
3775
  getExactDataOption = (dataName, key) => {
3484
- return getRuntime4().getExactDataOption(dataName, key);
3776
+ return getRuntime5().getExactDataOption(dataName, key);
3485
3777
  };
3486
3778
  getDataNames = () => {
3487
- return getRuntime4().getDataNames();
3779
+ return getRuntime5().getDataNames();
3488
3780
  };
3489
3781
  }
3490
3782
  });
@@ -3620,7 +3912,9 @@ function captureAuthorizationCatalog(value) {
3620
3912
  }
3621
3913
  catalog[key] = paths;
3622
3914
  }
3623
- return Object.freeze(catalog);
3915
+ const captured = Object.freeze(catalog);
3916
+ prepareCapturedOutputCatalog(captured);
3917
+ return captured;
3624
3918
  }
3625
3919
  function assertAuthorizationPath(path) {
3626
3920
  if (typeof path !== "string" || !isSafeOutputPath(path)) {
@@ -3805,10 +4099,12 @@ function resolveServiceAuthorization(input) {
3805
4099
  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
4100
  const responseSnapshots = input.parent && (nestedResponse || readResponse) ? callRecord(input.parent).responseSnapshots : listResponse ? Object.freeze({
3807
4101
  skipOutput: configuration.unsafeSkipListOutputSnapshotChecks === true,
3808
- skipNested: configuration.unsafeSkipListNestedDocumentSnapshotChecks === true
4102
+ skipNested: configuration.unsafeSkipListNestedDocumentSnapshotChecks === true,
4103
+ skipInitialOutputCopy: configuration.unsafeSkipListOutputSnapshotChecks === true && configuration.unsafeSkipListInitialOutputSnapshotCopy === true
3809
4104
  }) : readResponse ? Object.freeze({
3810
4105
  skipOutput: configuration.unsafeSkipReadOutputSnapshotChecks === true,
3811
- skipNested: configuration.unsafeSkipReadNestedDocumentSnapshotChecks === true
4106
+ skipNested: configuration.unsafeSkipReadNestedDocumentSnapshotChecks === true,
4107
+ skipInitialOutputCopy: configuration.unsafeSkipReadOutputSnapshotChecks === true && configuration.unsafeSkipReadInitialOutputSnapshotCopy === true
3812
4108
  }) : void 0;
3813
4109
  const call = Object.freeze(/* @__PURE__ */ Object.create(null));
3814
4110
  calls.set(call, {
@@ -3825,6 +4121,7 @@ function resolveServiceAuthorization(input) {
3825
4121
  nestedResponse,
3826
4122
  responseSnapshots,
3827
4123
  validateOutputSnapshots: responseSnapshots?.skipOutput !== true,
4124
+ skipInitialOutputSnapshotCopy: responseSnapshots?.skipInitialOutputCopy === true,
3828
4125
  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
4126
  });
3830
4127
  return call;
@@ -3854,6 +4151,10 @@ function requiresOutputSnapshotChecks(call, binding) {
3854
4151
  assertAuthorizationBinding(call, binding);
3855
4152
  return callRecord(call).validateOutputSnapshots;
3856
4153
  }
4154
+ function skipsInitialOutputSnapshotCopy(call) {
4155
+ const record3 = callRecord(call);
4156
+ return !record3.validateOutputSnapshots && record3.skipInitialOutputSnapshotCopy;
4157
+ }
3857
4158
  function readServiceAuthorizationHydration(call, binding) {
3858
4159
  assertAuthorizationBinding(call, binding);
3859
4160
  return copyAuthorizationValue({ hydration: callRecord(call).configuration.hydration }, true);
@@ -4307,7 +4608,7 @@ var init_virtual_projection = __esm({
4307
4608
 
4308
4609
  // src/acl/output-projection.ts
4309
4610
  function copyOutputDecisionFields(value) {
4310
- if (!Array.isArray(value) || import_node_util4.types.isProxy(value) || Object.getPrototypeOf(value) !== Array.prototype) return;
4611
+ if (!Array.isArray(value) || import_node_util5.types.isProxy(value) || Object.getPrototypeOf(value) !== Array.prototype) return;
4311
4612
  const length = Object.getOwnPropertyDescriptor(value, "length").value;
4312
4613
  if (length > 2e4) return;
4313
4614
  const fields = [];
@@ -4320,14 +4621,14 @@ function copyOutputDecisionFields(value) {
4320
4621
  }
4321
4622
  function readStaticOutputPlanFields(plan, authorization) {
4322
4623
  const record3 = staticPlanFields.get(plan);
4323
- if (!record3 || record3.authorization !== authorization || import_node_util4.types.isProxy(plan)) return;
4624
+ if (!record3 || record3.authorization !== authorization || import_node_util5.types.isProxy(plan)) return;
4324
4625
  const ownValue2 = (key) => {
4325
4626
  const slot = Object.getOwnPropertyDescriptor(plan, key);
4326
4627
  return slot && "value" in slot ? slot.value : void 0;
4327
4628
  };
4328
4629
  if (ownValue2("authorization") !== authorization || ownValue2("authorizationBinding") !== record3.binding) return;
4329
4630
  const children = ownValue2("childPlans");
4330
- if (children !== record3.children || import_node_util4.types.isProxy(children) || Reflect.ownKeys(children).length) return;
4631
+ if (children !== record3.children || import_node_util5.types.isProxy(children) || Reflect.ownKeys(children).length) return;
4331
4632
  const persisted = copyOutputDecisionFields(ownValue2("outputPersistedFields"));
4332
4633
  const virtuals = copyOutputDecisionFields(ownValue2("outputVirtualNames"));
4333
4634
  const same = (a, b) => a?.length === b.length && a.every((field, index) => field === b[index]);
@@ -4567,10 +4868,10 @@ function planCatalogProjection(args, outputFields = { mode: "request" }) {
4567
4868
  )
4568
4869
  };
4569
4870
  }
4570
- var import_node_util4, staticPlanFields;
4871
+ var import_node_util5, staticPlanFields;
4571
4872
  var init_output_projection = __esm({
4572
4873
  "src/acl/output-projection.ts"() {
4573
- import_node_util4 = require("util");
4874
+ import_node_util5 = require("util");
4574
4875
  init_query();
4575
4876
  init_authorization_snapshot();
4576
4877
  init_field_catalog();
@@ -4653,7 +4954,7 @@ function prepareOutputPath(policy, authorization, binding, path, access) {
4653
4954
  return prepared;
4654
4955
  }
4655
4956
  function ordinaryContainer(value) {
4656
- return value !== null && typeof value === "object" && !import_node_util5.types.isProxy(value) && Object.getPrototypeOf(value) === Object.prototype && Object.isFrozen(value);
4957
+ return value !== null && typeof value === "object" && !import_node_util6.types.isProxy(value) && Object.getPrototypeOf(value) === Object.prototype && Object.isFrozen(value);
4657
4958
  }
4658
4959
  function booleanRuleLookup(schema, path, access) {
4659
4960
  if (schema == null) return true;
@@ -4701,10 +5002,10 @@ function prepareStaticOutputPaths(authorization, binding, paths, access, request
4701
5002
  };
4702
5003
  });
4703
5004
  }
4704
- var import_node_util5, import_utils20, fieldPolicies;
5005
+ var import_node_util6, import_utils20, fieldPolicies;
4705
5006
  var init_output_field_policy = __esm({
4706
5007
  "src/acl/output-field-policy.ts"() {
4707
- import_node_util5 = require("util");
5008
+ import_node_util6 = require("util");
4708
5009
  import_utils20 = require("@web-ts-toolkit/utils");
4709
5010
  init_service_authorization();
4710
5011
  init_field_authorization();
@@ -4894,7 +5195,7 @@ function memoizeDocumentFieldDecision(handle, binding, field, evaluate) {
4894
5195
  return decision.promise;
4895
5196
  }
4896
5197
  function ordinaryDecisionBinding(binding) {
4897
- if (import_node_util6.types.isProxy(binding) || Object.getPrototypeOf(binding) !== Object.prototype) return false;
5198
+ if (import_node_util7.types.isProxy(binding) || Object.getPrototypeOf(binding) !== Object.prototype) return false;
4898
5199
  for (const key of ["request", "runtime", "model", "modelName", "scopePath"]) {
4899
5200
  const slot = Object.getOwnPropertyDescriptor(binding, key);
4900
5201
  if (slot && !("value" in slot)) return false;
@@ -5045,8 +5346,18 @@ function associateDocumentAuthorization(handle, binding, output) {
5045
5346
  authorizationError("output already associated");
5046
5347
  return;
5047
5348
  }
5349
+ if (skipsInitialOutputSnapshotCopy(stage.call) && ordinaryDecisionBinding(binding)) {
5350
+ if (requiresOutputSnapshotChecks(stage.call, binding))
5351
+ authorizationError("output snapshot copy requires skipped comparisons");
5352
+ const identities = tryOutputIdentitiesWithoutSnapshot(output);
5353
+ if (identities) {
5354
+ outputs.set(output, { handle, snapshotState: "omitted", identities, validateSnapshot: false });
5355
+ return;
5356
+ }
5357
+ }
5048
5358
  outputs.set(output, {
5049
5359
  handle,
5360
+ snapshotState: "copied",
5050
5361
  snapshot: copyAuthorizationValue(output, "document"),
5051
5362
  identities: outputIdentities(output),
5052
5363
  validateSnapshot: requiresOutputSnapshotChecks(stage.call, binding)
@@ -5134,10 +5445,10 @@ function createServiceOutputContext(diagnostic, handle, use) {
5134
5445
  });
5135
5446
  return context;
5136
5447
  }
5137
- var import_node_util6, import_mongoose5, stages, documents, outputs, unresolvedDocuments, owningDocuments;
5448
+ var import_node_util7, import_mongoose5, stages, documents, outputs, unresolvedDocuments, owningDocuments;
5138
5449
  var init_document_authorization = __esm({
5139
5450
  "src/acl/document-authorization.ts"() {
5140
- import_node_util6 = require("util");
5451
+ import_node_util7 = require("util");
5141
5452
  import_mongoose5 = require("mongoose");
5142
5453
  init_service_authorization();
5143
5454
  init_authorization_snapshot();
@@ -5224,10 +5535,11 @@ var init_request_work = __esm({
5224
5535
 
5225
5536
  // src/acl/model-output-planning.ts
5226
5537
  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);
5538
+ const defaultValue = key.startsWith("operationAccess.") ? (0, import_utils24.get)(configuration.operationAccessDefaults, key.slice("operationAccess.".length)) : void 0;
5539
+ return resolveNestedOption((path, fallback) => (0, import_utils24.get)(configuration, path, fallback), key, defaultValue);
5229
5540
  }
5230
- function captureModelAuthorizationConfiguration(runtime, modelName, options = runtime.getModelOptions(modelName), globalOptions = runtime.getGlobalOptions()) {
5541
+ function captureModelAuthorizationConfiguration(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime)) {
5542
+ options ??= runtime.getModelOptions(modelName);
5231
5543
  const model = runtime.getModelInstance(modelName);
5232
5544
  if (!model) return authorizationError(`unknown receiving model: ${modelName}`);
5233
5545
  const virtuals = options.virtuals;
@@ -5238,10 +5550,10 @@ function captureModelAuthorizationConfiguration(runtime, modelName, options = ru
5238
5550
  runtime,
5239
5551
  modelName,
5240
5552
  options,
5241
- globalOptions
5553
+ populatePolicyDefaults
5242
5554
  ),
5243
- requireOperationAccessForPopulateDependencies: globalOptions.requireOperationAccessForPopulateDependencies !== false,
5244
- requireOperationAccessForPopulateQueries: globalOptions.requireOperationAccessForPopulateQueries !== false,
5555
+ populatePolicyDefaults,
5556
+ ...resolvePopulatePolicy(options, populatePolicyDefaults),
5245
5557
  permissionSchema: options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema,
5246
5558
  virtuals,
5247
5559
  alwaysSelectFields: options.alwaysSelectFields,
@@ -5258,6 +5570,8 @@ function captureModelAuthorizationConfiguration(runtime, modelName, options = ru
5258
5570
  unsafeSkipReadOutputSnapshotChecks: options.unsafeSkipReadOutputSnapshotChecks === true,
5259
5571
  unsafeSkipListNestedDocumentSnapshotChecks: options.unsafeSkipListNestedDocumentSnapshotChecks === true,
5260
5572
  unsafeSkipReadNestedDocumentSnapshotChecks: options.unsafeSkipReadNestedDocumentSnapshotChecks === true,
5573
+ unsafeSkipListInitialOutputSnapshotCopy: options.unsafeSkipListInitialOutputSnapshotCopy === true,
5574
+ unsafeSkipReadInitialOutputSnapshotCopy: options.unsafeSkipReadInitialOutputSnapshotCopy === true,
5261
5575
  overrideFilter: options.overrideFilter,
5262
5576
  baseFilter: options.baseFilter,
5263
5577
  idField: options.idField,
@@ -5294,25 +5608,26 @@ function planModelOutputForHelper(args) {
5294
5608
  requestedSelect: args.select
5295
5609
  });
5296
5610
  }
5297
- var import_utils23;
5611
+ var import_utils24;
5298
5612
  var init_model_output_planning = __esm({
5299
5613
  "src/acl/model-output-planning.ts"() {
5300
- import_utils23 = require("@web-ts-toolkit/utils");
5614
+ import_utils24 = require("@web-ts-toolkit/utils");
5301
5615
  init_manager();
5302
5616
  init_field_catalog();
5303
5617
  init_authorization_snapshot();
5304
5618
  init_virtual_populate_dependencies();
5305
5619
  init_document_authorization();
5306
5620
  init_output_projection();
5621
+ init_populate_policy2();
5307
5622
  }
5308
5623
  });
5309
5624
 
5310
5625
  // src/core-shared.ts
5311
5626
  function isAndFilter(filter2) {
5312
- return !!filter2 && (0, import_utils24.isPlainObject)(filter2) && Object.keys(filter2).length === 1 && (0, import_utils24.isArray)(filter2.$and);
5627
+ return !!filter2 && (0, import_utils25.isPlainObject)(filter2) && Object.keys(filter2).length === 1 && (0, import_utils25.isArray)(filter2.$and);
5313
5628
  }
5314
5629
  function isMergeableClause(filter2) {
5315
- return !!filter2 && (0, import_utils24.isPlainObject)(filter2) && Object.keys(filter2).every((key) => !key.startsWith("$"));
5630
+ return !!filter2 && (0, import_utils25.isPlainObject)(filter2) && Object.keys(filter2).every((key) => !key.startsWith("$"));
5316
5631
  }
5317
5632
  function optimizeAndFilter(clausesInput) {
5318
5633
  const clauses = [];
@@ -5329,11 +5644,11 @@ function optimizeAndFilter(clausesInput) {
5329
5644
  const dedupeKey = (value) => {
5330
5645
  if (value instanceof RegExp) return `regexp:${JSON.stringify([value.source, value.flags])}`;
5331
5646
  if (value instanceof Date) return `date:${value.getTime()}`;
5332
- if ((0, import_utils24.isArray)(value)) {
5647
+ if ((0, import_utils25.isArray)(value)) {
5333
5648
  const entries = Array.from(value, dedupeKey);
5334
5649
  return entries.every((entry) => entry !== void 0) ? `array:${JSON.stringify(entries)}` : void 0;
5335
5650
  }
5336
- if ((0, import_utils24.isPlainObject)(value)) {
5651
+ if ((0, import_utils25.isPlainObject)(value)) {
5337
5652
  const entries = Object.keys(value).sort().map((key) => [key, dedupeKey(value[key])]);
5338
5653
  return entries.every(([, entry]) => entry !== void 0) ? `object:${JSON.stringify(entries)}` : void 0;
5339
5654
  }
@@ -5363,7 +5678,7 @@ function optimizeAndFilter(clausesInput) {
5363
5678
  }
5364
5679
  let canMerge = true;
5365
5680
  for (const [key, value] of Object.entries(clause)) {
5366
- if ((0, import_utils24.hasOwn)(mergedClause, key) && !(0, import_node_util7.isDeepStrictEqual)(mergedClause[key], value)) {
5681
+ if ((0, import_utils25.hasOwn)(mergedClause, key) && !(0, import_node_util8.isDeepStrictEqual)(mergedClause[key], value)) {
5367
5682
  canMerge = false;
5368
5683
  break;
5369
5684
  }
@@ -5374,24 +5689,24 @@ function optimizeAndFilter(clausesInput) {
5374
5689
  }
5375
5690
  Object.assign(mergedClause, clause);
5376
5691
  }
5377
- const finalClauses = (0, import_utils24.isEmpty)(mergedClause) ? remainingClauses : [mergedClause, ...remainingClauses];
5692
+ const finalClauses = (0, import_utils25.isEmpty)(mergedClause) ? remainingClauses : [mergedClause, ...remainingClauses];
5378
5693
  if (finalClauses.length === 0) return null;
5379
5694
  if (finalClauses.length === 1) return finalClauses[0];
5380
5695
  return { $and: finalClauses };
5381
5696
  }
5382
5697
  function normalizeFilter(filter2) {
5383
5698
  if (filter2 === false) return false;
5384
- if (!filter2 || !(0, import_utils24.isPlainObject)(filter2) || (0, import_utils24.isEmpty)(filter2)) return null;
5699
+ if (!filter2 || !(0, import_utils25.isPlainObject)(filter2) || (0, import_utils25.isEmpty)(filter2)) return null;
5385
5700
  if (!isAndFilter(filter2)) {
5386
5701
  return filter2;
5387
5702
  }
5388
5703
  return optimizeAndFilter(filter2.$and);
5389
5704
  }
5390
5705
  async function resolveIdentifierFilter(req, idField, resolveIdFilter, id) {
5391
- if ((0, import_utils24.isFunction)(resolveIdFilter)) {
5706
+ if ((0, import_utils25.isFunction)(resolveIdFilter)) {
5392
5707
  return await resolveIdFilter.call(req, id);
5393
5708
  }
5394
- if ((0, import_utils24.isString)(idField)) {
5709
+ if ((0, import_utils25.isString)(idField)) {
5395
5710
  return { [idField]: id };
5396
5711
  }
5397
5712
  return { _id: id };
@@ -5415,7 +5730,7 @@ async function resolveAccessFilterParts({
5415
5730
  }
5416
5731
  const overrideFilterFn = getOption(`overrideFilter.${access}`, null);
5417
5732
  const baseFilterFn = rows2.mode === "request" ? getOption(`baseFilter.${access}`, null) : null;
5418
- if (nextFilter !== false && (0, import_utils24.isFunction)(overrideFilterFn)) {
5733
+ if (nextFilter !== false && (0, import_utils25.isFunction)(overrideFilterFn)) {
5419
5734
  nextFilter = normalizeFilter(await overrideFilterFn.call(req, nextFilter, permissions));
5420
5735
  }
5421
5736
  if (nextFilter === false) return { transformed: false, scope: {}, filter: false };
@@ -5423,7 +5738,7 @@ async function resolveAccessFilterParts({
5423
5738
  const scope2 = rows2.mode === "scope" ? rows2.filter : {};
5424
5739
  return { transformed: nextFilter ?? {}, scope: scope2, filter: intersectFilters(nextFilter, scope2) };
5425
5740
  }
5426
- if (!(0, import_utils24.isFunction)(baseFilterFn)) return { transformed: nextFilter ?? {}, scope: {}, filter: nextFilter ?? {} };
5741
+ if (!(0, import_utils25.isFunction)(baseFilterFn)) return { transformed: nextFilter ?? {}, scope: {}, filter: nextFilter ?? {} };
5427
5742
  const cached = cache.get(cacheKey);
5428
5743
  const reusable = cached?.resolver === baseFilterFn;
5429
5744
  const baseFilter = normalizeFilter(
@@ -5458,34 +5773,34 @@ async function setRequestPermissions(req) {
5458
5773
  if (owner === activeRuntime) return;
5459
5774
  if (hasFieldValue && owner === void 0) return;
5460
5775
  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 };
5776
+ const permissions = (0, import_utils25.isFunction)(globalPermissions) ? await globalPermissions.call(req, req) : void 0;
5777
+ if ((0, import_utils25.isPlainObject)(permissions)) req[requestPermissionField] = permissions;
5778
+ else if ((0, import_utils25.isArray)(permissions)) req[requestPermissionField] = (0, import_utils25.arrayToRecord)(permissions);
5779
+ else if ((0, import_utils25.isString)(permissions)) req[requestPermissionField] = { [permissions]: true };
5465
5780
  else req[requestPermissionField] = {};
5466
5781
  owners.set(requestPermissionField, activeRuntime);
5467
5782
  }
5468
5783
  async function evaluateRouteGuard(req, permissions, routeGuard) {
5469
5784
  const phas = (key) => permissions.has(key);
5470
5785
  const { stringHandler, arrayHandler } = createValidator(phas);
5471
- if ((0, import_utils24.isBoolean)(routeGuard)) {
5786
+ if ((0, import_utils25.isBoolean)(routeGuard)) {
5472
5787
  return routeGuard === true;
5473
5788
  }
5474
- if ((0, import_utils24.isString)(routeGuard)) {
5789
+ if ((0, import_utils25.isString)(routeGuard)) {
5475
5790
  return stringHandler(routeGuard);
5476
5791
  }
5477
- if ((0, import_utils24.isArray)(routeGuard)) {
5792
+ if ((0, import_utils25.isArray)(routeGuard)) {
5478
5793
  return arrayHandler(routeGuard);
5479
5794
  }
5480
- if ((0, import_utils24.isFunction)(routeGuard)) {
5795
+ if ((0, import_utils25.isFunction)(routeGuard)) {
5481
5796
  return routeGuard.call(req, permissions);
5482
5797
  }
5483
5798
  return false;
5484
5799
  }
5485
5800
  async function callHookChain(req, hook, doc, permissions, context) {
5486
- const hooks = (0, import_utils24.castArray)(hook);
5801
+ const hooks = (0, import_utils25.castArray)(hook);
5487
5802
  for (let x = 0; x < hooks.length; x++) {
5488
- if ((0, import_utils24.isFunction)(hooks[x])) {
5803
+ if ((0, import_utils25.isFunction)(hooks[x])) {
5489
5804
  doc = await hooks[x].call(req, doc, permissions, context);
5490
5805
  }
5491
5806
  }
@@ -5505,23 +5820,23 @@ async function collectSchemaFields({
5505
5820
  for (let x = 0; x < keys2.length; x++) {
5506
5821
  const key = keys2[x];
5507
5822
  const value = extractScopedOutputRule(permissionSchema, key, access);
5508
- if ((0, import_utils24.isBoolean)(value)) {
5823
+ if ((0, import_utils25.isBoolean)(value)) {
5509
5824
  if (value) fields.push(key);
5510
- } else if ((0, import_utils24.isString)(value)) {
5825
+ } else if ((0, import_utils25.isString)(value)) {
5511
5826
  if (stringHandler(value)) fields.push(key);
5512
- } else if ((0, import_utils24.isArray)(value)) {
5827
+ } else if ((0, import_utils25.isArray)(value)) {
5513
5828
  if (arrayHandler(value)) fields.push(key);
5514
- } else if ((0, import_utils24.isFunction)(value)) {
5829
+ } else if ((0, import_utils25.isFunction)(value)) {
5515
5830
  if (await value.call(req, ...functionArgs)) fields.push(key);
5516
5831
  }
5517
5832
  }
5518
5833
  return fields;
5519
5834
  }
5520
- var import_utils24, import_node_util7, permissionFieldOwners;
5835
+ var import_utils25, import_node_util8, permissionFieldOwners;
5521
5836
  var init_core_shared = __esm({
5522
5837
  "src/core-shared.ts"() {
5523
- import_utils24 = require("@web-ts-toolkit/utils");
5524
- import_node_util7 = require("util");
5838
+ import_utils25 = require("@web-ts-toolkit/utils");
5839
+ import_node_util8 = require("util");
5525
5840
  init_helpers();
5526
5841
  init_options();
5527
5842
  init_runtime_context();
@@ -5772,6 +6087,13 @@ var init_logger_helpers = __esm({
5772
6087
 
5773
6088
  // src/acl/populate-target.ts
5774
6089
  function setPopulateTargetMeta(entry, meta) {
6090
+ if (meta.fetchBinding)
6091
+ Object.defineProperty(entry, "model", {
6092
+ value: meta.fetchBinding.model,
6093
+ enumerable: true,
6094
+ writable: false,
6095
+ configurable: false
6096
+ });
5775
6097
  Object.defineProperty(entry, POPULATE_TARGET_PLAN, {
5776
6098
  value: meta,
5777
6099
  enumerable: false,
@@ -5899,7 +6221,7 @@ function equivalentVirtualPopulatePredicate(left, right) {
5899
6221
  )
5900
6222
  );
5901
6223
  }
5902
- return (0, import_node_util8.isDeepStrictEqual)(left, right);
6224
+ return (0, import_node_util9.isDeepStrictEqual)(left, right);
5903
6225
  }
5904
6226
  function createVirtualPopulateBatch(owner) {
5905
6227
  const batch = Object.freeze(/* @__PURE__ */ Object.create(null));
@@ -6274,11 +6596,11 @@ async function loadVirtualPopulateOutputRows(owner, inputs, plan, publicPopulate
6274
6596
  }
6275
6597
  return output;
6276
6598
  }
6277
- var import_mongoose7, import_node_util8, import_utils28, batches, rows, outputRows, fetchedPublicIdentities, publicViewIdentities, familyRawFetches, addressKey, storage, originalRef, copyOriginalValue, readPolicy, compatible, idKey, logUnavailable;
6599
+ var import_mongoose7, import_node_util9, import_utils28, batches, rows, outputRows, fetchedPublicIdentities, publicViewIdentities, familyRawFetches, addressKey, storage, originalRef, copyOriginalValue, readPolicy, compatible, idKey, logUnavailable;
6278
6600
  var init_virtual_populate_execution = __esm({
6279
6601
  "src/acl/virtual-populate-execution.ts"() {
6280
6602
  import_mongoose7 = require("mongoose");
6281
- import_node_util8 = require("util");
6603
+ import_node_util9 = require("util");
6282
6604
  import_utils28 = require("@web-ts-toolkit/utils");
6283
6605
  init_cache();
6284
6606
  init_core_shared();
@@ -6550,7 +6872,7 @@ function helperPlan(authorization, binding) {
6550
6872
  return planAuthorizedModelProjection({ authorization, binding, effectiveSelect: [] });
6551
6873
  }
6552
6874
  function primitiveHelperFields(source, plan) {
6553
- if (import_node_util9.types.isProxy(source)) return;
6875
+ if (import_node_util10.types.isProxy(source)) return;
6554
6876
  const canonical = readStaticOutputPlanFields(plan, plan.authorization);
6555
6877
  if (!canonical) return;
6556
6878
  const fields = [];
@@ -6681,10 +7003,10 @@ async function filterModelOutputForHelper(args) {
6681
7003
  });
6682
7004
  return filterExistingOutput(source, plan, handle, false);
6683
7005
  }
6684
- var import_node_util9, import_utils29;
7006
+ var import_node_util10, import_utils29;
6685
7007
  var init_output_field_filter = __esm({
6686
7008
  "src/acl/output-field-filter.ts"() {
6687
- import_node_util9 = require("util");
7009
+ import_node_util10 = require("util");
6688
7010
  import_utils29 = require("@web-ts-toolkit/utils");
6689
7011
  init_permissions_alias();
6690
7012
  init_document();
@@ -7404,7 +7726,7 @@ init_options();
7404
7726
  init_permission();
7405
7727
 
7406
7728
  // src/services/base.ts
7407
- var import_utils25 = require("@web-ts-toolkit/utils");
7729
+ var import_utils26 = require("@web-ts-toolkit/utils");
7408
7730
  init_options();
7409
7731
  init_helpers();
7410
7732
  init_document();
@@ -7972,14 +8294,111 @@ function isCorrelatedInclude(value) {
7972
8294
  // src/services/base.ts
7973
8295
  init_request_complexity();
7974
8296
 
7975
- // src/acl/model-service-owner.ts
8297
+ // src/model.ts
7976
8298
  var import_node_async_hooks3 = require("async_hooks");
8299
+ var import_utils23 = require("@web-ts-toolkit/utils");
8300
+ init_runtime_context();
8301
+ init_runtime();
8302
+ var capturedModelConstruction = new import_node_async_hooks3.AsyncLocalStorage();
8303
+ function withCapturedPopulateModel(runtime, modelName, model, construct) {
8304
+ return capturedModelConstruction.run({ runtime, modelName, model }, construct);
8305
+ }
8306
+ function admitModelPersistence(adapter, scheduler) {
8307
+ return {
8308
+ modelName: adapter.modelName,
8309
+ mongooseModel: adapter.mongooseModel,
8310
+ new: () => adapter.new(),
8311
+ // Mongoose create(array) otherwise starts all document saves at once. Keep
8312
+ // the adapter's array input/output contract, with one permit per item; all
8313
+ // items are submitted even if one rejects, as with unordered create(array).
8314
+ create: (data) => Array.isArray(data) ? Promise.all(data.map((item) => scheduler.work(async () => (await adapter.create([item]))[0]))) : scheduler.work(() => adapter.create(data)),
8315
+ find: (props) => scheduler.work(() => adapter.find(props)),
8316
+ findOne: (props) => scheduler.work(() => adapter.findOne(props)),
8317
+ exists: (filter2) => scheduler.work(() => adapter.exists(filter2)),
8318
+ countDocuments: (filter2) => scheduler.work(() => adapter.countDocuments(filter2)),
8319
+ distinct: (field, conditions) => scheduler.work(() => adapter.distinct(field, conditions)),
8320
+ aggregate: (pipeline) => scheduler.work(() => adapter.aggregate(pipeline)),
8321
+ // Casting builds no persistence work and must not acquire a recursive permit.
8322
+ ...adapter.castFilter ? { castFilter: (filter2) => adapter.castFilter(filter2) } : {}
8323
+ };
8324
+ }
8325
+ var Model = class {
8326
+ constructor(modelName, runtime) {
8327
+ this.modelName = modelName;
8328
+ this.runtime = runtime ?? null;
8329
+ const resolvedRuntime = runtime ?? getActiveRuntime() ?? defaultRuntime;
8330
+ const captured = capturedModelConstruction.getStore();
8331
+ const registered = captured?.runtime === resolvedRuntime && captured.modelName === modelName ? captured.model : resolvedRuntime.getModelInstance(modelName);
8332
+ if (!registered) {
8333
+ throw new Error(
8334
+ `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this runtime.`
8335
+ );
8336
+ }
8337
+ this.mongooseModel = registered;
8338
+ if (!this.mongooseModel) return;
8339
+ }
8340
+ new() {
8341
+ const doc = new this.mongooseModel();
8342
+ return doc;
8343
+ }
8344
+ create(data) {
8345
+ return this.mongooseModel.create(data);
8346
+ }
8347
+ find({ filter: filter2, select, sort, populate, limit, hardLimit, skip, lean }) {
8348
+ const builder = this.mongooseModel.find(filter2);
8349
+ if (select) builder.select(select);
8350
+ if (skip) builder.skip(Number(skip));
8351
+ const normalizedLimit = Number(limit);
8352
+ if (Number.isSafeInteger(normalizedLimit) && normalizedLimit > 0) {
8353
+ builder.limit(normalizedLimit);
8354
+ } else if (Number.isSafeInteger(hardLimit) && Number(hardLimit) > 0) {
8355
+ builder.limit(Number(hardLimit));
8356
+ }
8357
+ if (sort) builder.sort(sort);
8358
+ if (populate) builder.populate(populate);
8359
+ if (lean) builder.lean();
8360
+ return builder;
8361
+ }
8362
+ findOne({ filter: filter2, select, sort, populate, lean }) {
8363
+ const builder = this.mongooseModel.findOne(filter2);
8364
+ if (select) builder.select(select);
8365
+ if (sort) builder.sort(sort);
8366
+ if (populate) builder.populate(populate);
8367
+ if (lean) builder.lean();
8368
+ return builder;
8369
+ }
8370
+ exists(filter2) {
8371
+ if (!filter2) return null;
8372
+ return this.findOne({ filter: filter2 }).select("_id").lean();
8373
+ }
8374
+ // see https://mongoosejs.com/docs/api.html#query_Query-countDocuments
8375
+ countDocuments(filter2 = {}) {
8376
+ return this.mongooseModel.countDocuments(filter2);
8377
+ }
8378
+ /** Cast a copy using this model's query schema/setters, without executing query middleware or persistence. */
8379
+ castFilter(filter2) {
8380
+ const query = this.mongooseModel.countDocuments((0, import_utils23.cloneDeep)(filter2));
8381
+ return query.cast(this.mongooseModel);
8382
+ }
8383
+ // see https://mongoosejs.com/docs/api.html#model_Model.distinct
8384
+ distinct(field, conditions = {}) {
8385
+ return this.mongooseModel.distinct(field, conditions);
8386
+ }
8387
+ aggregate(pipeline) {
8388
+ return this.mongooseModel.aggregate(pipeline);
8389
+ }
8390
+ };
8391
+ var model_default = Model;
8392
+
8393
+ // src/acl/model-service-owner.ts
8394
+ var import_node_async_hooks4 = require("async_hooks");
7977
8395
  init_runtime();
7978
8396
  init_runtime_context();
8397
+ init_populate_policy2();
7979
8398
  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();
8399
+ var construction = new import_node_async_hooks4.AsyncLocalStorage();
8400
+ var dispatch = new import_node_async_hooks4.AsyncLocalStorage();
8401
+ var operationGuard = new import_node_async_hooks4.AsyncLocalStorage();
7983
8402
  function withCapturedModelOperationGuard(core, modelName, access, guard2, permissions, run) {
7984
8403
  return operationGuard.run({ captured: { core, modelName, access, guard: guard2, permissions } }, run);
7985
8404
  }
@@ -8028,15 +8447,16 @@ function bindModelOwnerMethods(receiver, runtime) {
8028
8447
  }
8029
8448
  }
8030
8449
  }
8031
- function modelServiceOptions(receiver, read) {
8450
+ function modelServiceOptions(receiver, runtime, read) {
8451
+ modelServicePopulatePolicyDefaults(receiver, runtime);
8032
8452
  const call = dispatch.getStore();
8033
8453
  if (call?.receiver !== receiver) return read();
8034
8454
  return call.options ??= read();
8035
8455
  }
8036
- function modelServiceGlobalOptions(receiver, runtime) {
8456
+ function modelServicePopulatePolicyDefaults(receiver, runtime) {
8037
8457
  const call = dispatch.getStore();
8038
- if (call?.receiver !== receiver) return runtime.getGlobalOptions();
8039
- return call.globalOptions ??= runtime.getGlobalOptions();
8458
+ if (call?.receiver !== receiver) return capturePopulatePolicyDefaults(runtime);
8459
+ return call.populatePolicyDefaults ??= capturePopulatePolicyDefaults(runtime);
8040
8460
  }
8041
8461
 
8042
8462
  // src/services/base.ts
@@ -8190,27 +8610,6 @@ function castCountGroups(input, values) {
8190
8610
  // src/services/base.ts
8191
8611
  init_service_authorization();
8192
8612
 
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
8613
  // src/acl/related-execution.ts
8215
8614
  init_public_admission();
8216
8615
  init_model_output_planning();
@@ -8458,9 +8857,9 @@ function resolveExistsOptions(service, options = {}) {
8458
8857
 
8459
8858
  // src/services/model-service-intent.ts
8460
8859
  function captureModelServiceIntent(owner, method, args = {}, options = {}) {
8461
- const defaults = owner.defaults;
8860
+ const defaults2 = owner.defaults;
8462
8861
  const posture = owner.getPermissionsPosture();
8463
- const service = { defaults, getPermissionsPosture: () => posture };
8862
+ const service = { defaults: defaults2, getPermissionsPosture: () => posture };
8464
8863
  switch (method) {
8465
8864
  case "find":
8466
8865
  return deepIsolateValue({ args: resolveFindArgs(service, args), options: resolveFindOptions(service, options) });
@@ -8491,6 +8890,7 @@ function captureModelServiceIntent(owner, method, args = {}, options = {}) {
8491
8890
  }
8492
8891
 
8493
8892
  // src/acl/related-execution.ts
8893
+ init_populate_policy2();
8494
8894
  init_service_authorization();
8495
8895
  function staticObjectIdReference(runtime, source, path, target) {
8496
8896
  const model = runtime.getModelInstance(source), related = runtime.getModelInstance(target);
@@ -8507,7 +8907,7 @@ function staticObjectIdReference(runtime, source, path, target) {
8507
8907
  const scalar = type?.instance === "Array" ? type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster : type;
8508
8908
  return scalar?.instance === "ObjectId" && (type?.options?.ref ?? scalar.options?.ref) === target && type?.options?.refPath === void 0 && scalar.options?.refPath === void 0;
8509
8909
  }
8510
- function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalOptions = runtime.getGlobalOptions()) {
8910
+ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime)) {
8511
8911
  if (depth > 32) authorizationError("related descriptor depth exceeded");
8512
8912
  assertPublicAdmission(args.populate, "populate");
8513
8913
  assertPublicAdmission(args.include, "include");
@@ -8516,20 +8916,32 @@ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalO
8516
8916
  for (const entry of entries(args.populate)) {
8517
8917
  const path = typeof entry === "string" ? entry : entry.path;
8518
8918
  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}`);
8919
+ const target = capturePopulateTargetBinding(runtime, modelName, path);
8920
+ if (target) {
8522
8921
  targets.push({
8523
8922
  path,
8524
- modelName: model,
8525
- configuration: captureModelAuthorizationConfiguration(runtime, model, target.options, globalOptions),
8526
- staticObjectIdReference: staticObjectIdReference(runtime, modelName, path, model)
8923
+ modelName: target.modelName,
8924
+ model: target.model,
8925
+ configuration: captureModelAuthorizationConfiguration(
8926
+ runtime,
8927
+ target.modelName,
8928
+ target.options,
8929
+ populatePolicyDefaults
8930
+ ),
8931
+ staticObjectIdReference: staticObjectIdReference(runtime, modelName, path, target.modelName)
8527
8932
  });
8528
8933
  }
8529
8934
  }
8530
8935
  for (const entry of entries(args.include)) {
8531
8936
  if (!runtime.hasModel(entry.model)) authorizationError(`Model ${entry.model} not found`);
8532
- const configuration = captureModelAuthorizationConfiguration(runtime, entry.model, void 0, globalOptions);
8937
+ const model = runtime.getModelInstance(entry.model);
8938
+ if (!model) authorizationError(`unknown receiving model: ${entry.model}`);
8939
+ const configuration = captureModelAuthorizationConfiguration(
8940
+ runtime,
8941
+ entry.model,
8942
+ void 0,
8943
+ populatePolicyDefaults
8944
+ );
8533
8945
  const queryIntent = entry.op === "count" ? void 0 : captureModelServiceIntent(
8534
8946
  {
8535
8947
  defaults: configuration.defaults ?? {},
@@ -8551,6 +8963,7 @@ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalO
8551
8963
  targets.push({
8552
8964
  path: entry.path,
8553
8965
  modelName: entry.model,
8966
+ model,
8554
8967
  kind: entry.op === "count" ? "count" : "output",
8555
8968
  configuration,
8556
8969
  queryIntent,
@@ -8560,7 +8973,7 @@ function captureRelatedTargets(runtime, modelName, args = {}, depth = 0, globalO
8560
8973
  entry.model,
8561
8974
  queryIntent?.args ?? entry.args ?? {},
8562
8975
  depth + 1,
8563
- globalOptions
8976
+ populatePolicyDefaults
8564
8977
  )
8565
8978
  });
8566
8979
  }
@@ -8577,7 +8990,8 @@ function createRelatedExecution(receiver, access, parent, binding, path) {
8577
8990
  const captured = readServiceAuthorization(parent, binding);
8578
8991
  const target = captured.relatedTargets.find((entry) => entry.path === path);
8579
8992
  const policy = captured.authorization.related[path];
8580
- if ((target || policy) && (!target || target.modelName !== getServiceExecutors(receiver).binding().modelName))
8993
+ const receiving = getServiceExecutors(receiver).binding();
8994
+ if (policy && !target || target && (target.modelName !== receiving.modelName || target.model !== void 0 && target.model !== receiving.model))
8581
8995
  authorizationError(`related model mismatch: ${path}`);
8582
8996
  const execution = createServiceExecution(
8583
8997
  receiver,
@@ -8712,20 +9126,20 @@ var copyAuthorizedOutput = (value) => {
8712
9126
  transferDocumentAuthorizationGraph(value, copy);
8713
9127
  return copy;
8714
9128
  };
8715
- var isVirtualContainerValueForGuard = (value) => (0, import_utils25.isPlainObject)(value) && "sub" in value;
9129
+ var isVirtualContainerValueForGuard = (value) => (0, import_utils26.isPlainObject)(value) && "sub" in value;
8716
9130
  var getScopeVirtualsForGuard = (rootVirtuals, scopePath) => {
8717
- if (!rootVirtuals || !(0, import_utils25.isPlainObject)(rootVirtuals)) return null;
9131
+ if (!rootVirtuals || !(0, import_utils26.isPlainObject)(rootVirtuals)) return null;
8718
9132
  if (scopePath.length === 0) return rootVirtuals;
8719
9133
  let current = rootVirtuals;
8720
9134
  for (let i = 0; i < scopePath.length; i += 2) {
8721
9135
  const field = scopePath[i];
8722
9136
  const subMarker = scopePath[i + 1];
8723
9137
  if (!field || subMarker !== "sub") return null;
8724
- if (!(0, import_utils25.isPlainObject)(current)) return null;
9138
+ if (!(0, import_utils26.isPlainObject)(current)) return null;
8725
9139
  const container = current[field];
8726
9140
  if (!isVirtualContainerValueForGuard(container)) return null;
8727
9141
  current = container.sub;
8728
- if (!(0, import_utils25.isPlainObject)(current)) return null;
9142
+ if (!(0, import_utils26.isPlainObject)(current)) return null;
8729
9143
  }
8730
9144
  return current;
8731
9145
  };
@@ -8791,7 +9205,7 @@ var sanitizeSubScopeVirtualKeys = (data, snapshot, sub) => {
8791
9205
  for (const entry of value) stripScope(entry, currentScope);
8792
9206
  return;
8793
9207
  }
8794
- if (!(0, import_utils25.isPlainObject)(value)) return;
9208
+ if (!(0, import_utils26.isPlainObject)(value)) return;
8795
9209
  const record3 = value;
8796
9210
  const leaves = getScopeVirtualLeafNames(snapshot, currentScope);
8797
9211
  for (const leaf of leaves) {
@@ -8804,7 +9218,7 @@ var sanitizeSubScopeVirtualKeys = (data, snapshot, sub) => {
8804
9218
  for (const key of Object.keys(record3)) {
8805
9219
  if (leaves.has(key) || containers.has(key)) continue;
8806
9220
  const child = record3[key];
8807
- if (Array.isArray(child) || (0, import_utils25.isPlainObject)(child)) {
9221
+ if (Array.isArray(child) || (0, import_utils26.isPlainObject)(child)) {
8808
9222
  stripScope(child, currentScope);
8809
9223
  }
8810
9224
  }
@@ -8816,7 +9230,7 @@ var LOGICAL_FILTER_KEYS = /* @__PURE__ */ new Set(["$and", "$or", "$nor"]);
8816
9230
  var isOperatorKey = (key) => key.startsWith("$");
8817
9231
  var REMOVED_VIRTUAL_FILTER = /* @__PURE__ */ Symbol("removed virtual filter clause");
8818
9232
  var rewriteFilterObject = (value, visit) => {
8819
- if (!(0, import_utils25.isPlainObject)(value)) return value;
9233
+ if (!(0, import_utils26.isPlainObject)(value)) return value;
8820
9234
  let changed = false;
8821
9235
  const entries = [];
8822
9236
  for (const [key, child] of Object.entries(value)) {
@@ -8847,7 +9261,7 @@ var resolveVirtualFilterField = (path, scope2) => {
8847
9261
  if (!Object.hasOwn(scope2, segment) || scope2[segment] === void 0) return null;
8848
9262
  const definition = scope2[segment];
8849
9263
  if (!isVirtualContainerValueForGuard(definition)) return REMOVED_VIRTUAL_FILTER;
8850
- scope2 = (0, import_utils25.isPlainObject)(definition.sub) ? definition.sub : null;
9264
+ scope2 = (0, import_utils26.isPlainObject)(definition.sub) ? definition.sub : null;
8851
9265
  inContainer = true;
8852
9266
  }
8853
9267
  return scope2;
@@ -8859,7 +9273,7 @@ var stripVirtualFilterOperator = (key, value, scope2) => {
8859
9273
  }
8860
9274
  if (key === "$all") {
8861
9275
  return rewriteFilterClauses(value, (entry) => {
8862
- if (!(0, import_utils25.isPlainObject)(entry) || Object.keys(entry).length !== 1 || !Object.hasOwn(entry, "$elemMatch")) return entry;
9276
+ if (!(0, import_utils26.isPlainObject)(entry) || Object.keys(entry).length !== 1 || !Object.hasOwn(entry, "$elemMatch")) return entry;
8863
9277
  return rewriteFilterObject(entry, (operator, operand) => stripVirtualFilterOperator(operator, operand, scope2));
8864
9278
  });
8865
9279
  }
@@ -8874,7 +9288,7 @@ var stripVirtualFilterQuery = (value, scope2, element = false) => {
8874
9288
  if (isOperatorKey(key)) return element ? stripVirtualFilterOperator(key, child, scope2) : child;
8875
9289
  const fieldScope = resolveVirtualFilterField(key, scope2);
8876
9290
  if (fieldScope === REMOVED_VIRTUAL_FILTER) return REMOVED_VIRTUAL_FILTER;
8877
- if (!fieldScope || !(0, import_utils25.isPlainObject)(child)) return child;
9291
+ if (!fieldScope || !(0, import_utils26.isPlainObject)(child)) return child;
8878
9292
  if (Object.keys(child).some(isOperatorKey)) {
8879
9293
  return rewriteFilterObject(
8880
9294
  child,
@@ -8896,9 +9310,9 @@ var stripSubVirtualKeysFromFilter = (filter2, snapshot, sub) => {
8896
9310
  function getCorrelatedTemplateDepth(includes) {
8897
9311
  let max = 0;
8898
9312
  const visit = (entries, depth) => {
8899
- const list = (0, import_utils25.castArray)(entries).filter(Boolean);
9313
+ const list = (0, import_utils26.castArray)(entries).filter(Boolean);
8900
9314
  for (const entry of list) {
8901
- if (!(0, import_utils25.isPlainObject)(entry)) continue;
9315
+ if (!(0, import_utils26.isPlainObject)(entry)) continue;
8902
9316
  max = Math.max(max, depth);
8903
9317
  const nested = entry.args?.include;
8904
9318
  if (nested !== void 0) {
@@ -8923,11 +9337,11 @@ function validateClientFilter(filter2) {
8923
9337
  }
8924
9338
  const blockedOperators = /* @__PURE__ */ new Set(["$where", "$expr", "$function", "$accumulator"]);
8925
9339
  const visit = (value, path) => {
8926
- if ((0, import_utils25.isArray)(value)) {
9340
+ if ((0, import_utils26.isArray)(value)) {
8927
9341
  value.forEach((item, index) => visit(item, `${path}[${index}]`));
8928
9342
  return;
8929
9343
  }
8930
- if (!(0, import_utils25.isPlainObject)(value)) return;
9344
+ if (!(0, import_utils26.isPlainObject)(value)) return;
8931
9345
  Object.entries(value).forEach(([key, child]) => {
8932
9346
  const nextPath = path ? `${path}.${key}` : key;
8933
9347
  if (blockedOperators.has(key)) {
@@ -9075,34 +9489,37 @@ var Base = class {
9075
9489
  });
9076
9490
  }
9077
9491
  async getAuthorizedTargetService(modelName, op, path, parentAuthorization) {
9078
- if (hasModelCoreOwner(this.requestCore) && !this.requestRuntime.hasModel(modelName)) {
9492
+ const binding = parentAuthorization ? this.relatedBinding() : void 0;
9493
+ const captured = parentAuthorization ? readServiceAuthorization(parentAuthorization, binding) : void 0;
9494
+ const target = captured?.relatedTargets.find((entry) => entry.path === path);
9495
+ const policy = path ? captured?.authorization.related[path] : void 0;
9496
+ if (target && target.modelName !== modelName)
9497
+ this.throwClientRequestError("bad_request" /* BadRequest */, `related model mismatch: ${path}`);
9498
+ if (hasModelCoreOwner(this.requestCore) && !target?.model && !this.requestRuntime.hasModel(modelName)) {
9079
9499
  this.throwClientRequestError("bad_request" /* BadRequest */, `Model ${modelName} not found`);
9080
9500
  }
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
9501
  const allowed = policy?.operation.mode === "grant" || (target ? await getRequestWorkState(this.req, this.requestRuntime).hookGate.run(
9085
9502
  () => withCapturedModelOperationGuard(
9086
9503
  this.requestCore,
9087
9504
  modelName,
9088
9505
  op,
9089
9506
  target.operationGuard,
9090
- getAuthorizationPermissions(parentAuthorization, this.relatedBinding()),
9507
+ getAuthorizationPermissions(parentAuthorization, binding),
9091
9508
  () => this.requestCore.isAllowed(modelName, op)
9092
9509
  )
9093
9510
  ) : await this.requestCore.isAllowed(modelName, op));
9094
9511
  if (!allowed) {
9095
9512
  this.throwClientRequestError("unauthorized" /* Unauthorized */, "Unauthorized");
9096
9513
  }
9097
- return this.requestCore.getPublicService(modelName);
9514
+ return target?.model ? withCapturedPopulateModel(
9515
+ this.requestRuntime,
9516
+ modelName,
9517
+ target.model,
9518
+ () => this.requestCore.getPublicService(modelName)
9519
+ ) : this.requestCore.getPublicService(modelName);
9098
9520
  }
9099
9521
  relatedBinding() {
9100
- return {
9101
- request: this.req,
9102
- runtime: this.requestRuntime,
9103
- model: this.requestRuntime.getModelInstance(this.modelName),
9104
- modelName: this.modelName
9105
- };
9522
+ return getServiceExecutors(this).binding();
9106
9523
  }
9107
9524
  relatedExecution(svc, include, parentAuthorization) {
9108
9525
  const op = include.op;
@@ -9132,7 +9549,7 @@ var Base = class {
9132
9549
  }
9133
9550
  processInclude(include, authorization) {
9134
9551
  assertPublicAdmission(include, "include");
9135
- const items = (0, import_utils25.compact)((0, import_utils25.castArray)(include));
9552
+ const items = (0, import_utils26.compact)((0, import_utils26.castArray)(include));
9136
9553
  const legacy = [];
9137
9554
  const correlated = [];
9138
9555
  const correlatedReferenceFields = [];
@@ -9168,23 +9585,23 @@ var Base = class {
9168
9585
  else this.assertIncludeOutputPaths([...legacy, ...correlated]);
9169
9586
  let includeLocalFields = [];
9170
9587
  let includePaths = [];
9171
- (0, import_utils25.forEach)(legacy, (inc) => {
9588
+ (0, import_utils26.forEach)(legacy, (inc) => {
9172
9589
  includeLocalFields.push(inc.localField);
9173
9590
  includePaths.push(inc.path);
9174
9591
  });
9175
- includeLocalFields = (0, import_utils25.uniq)((0, import_utils25.compact)(includeLocalFields));
9176
- includePaths = (0, import_utils25.uniq)((0, import_utils25.compact)(includePaths));
9592
+ includeLocalFields = (0, import_utils26.uniq)((0, import_utils26.compact)(includeLocalFields));
9593
+ includePaths = (0, import_utils26.uniq)((0, import_utils26.compact)(includePaths));
9177
9594
  return {
9178
9595
  includes: legacy,
9179
9596
  correlatedIncludes: correlated,
9180
9597
  includeLocalFields,
9181
9598
  includePaths,
9182
- correlatedReferenceFields: (0, import_utils25.uniq)((0, import_utils25.compact)(correlatedReferenceFields))
9599
+ correlatedReferenceFields: (0, import_utils26.uniq)((0, import_utils26.compact)(correlatedReferenceFields))
9183
9600
  };
9184
9601
  }
9185
9602
  validateIncludeOutputPath(path, modelName, configuration) {
9186
9603
  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) {
9604
+ 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
9605
  this.throwClientRequestError(
9189
9606
  "bad_request" /* BadRequest */,
9190
9607
  `Include output path ${path} overlaps document permission field ${permissionField} on model ${modelName}`
@@ -9209,9 +9626,9 @@ var Base = class {
9209
9626
  const walk = (node, prefix) => {
9210
9627
  for (const [key, value] of Object.entries(node)) {
9211
9628
  if (value === void 0) continue;
9212
- if ((0, import_utils25.isPlainObject)(value) && "sub" in value) {
9629
+ if ((0, import_utils26.isPlainObject)(value) && "sub" in value) {
9213
9630
  const sub = value.sub;
9214
- if ((0, import_utils25.isPlainObject)(sub)) walk(sub, prefix ? `${prefix}.${key}` : key);
9631
+ if ((0, import_utils26.isPlainObject)(sub)) walk(sub, prefix ? `${prefix}.${key}` : key);
9215
9632
  continue;
9216
9633
  }
9217
9634
  out.push(prefix ? `${prefix}.${key}` : key);
@@ -9264,7 +9681,7 @@ var Base = class {
9264
9681
  this.throwClientRequestError("bad_request" /* BadRequest */, `Model ${modelName} not found`);
9265
9682
  }
9266
9683
  for (const entry of entries) {
9267
- if (!(0, import_utils25.isPlainObject)(entry)) continue;
9684
+ if (!(0, import_utils26.isPlainObject)(entry)) continue;
9268
9685
  const models = visited.get(entry) ?? /* @__PURE__ */ new Set();
9269
9686
  if (models.has(modelName)) continue;
9270
9687
  models.add(modelName);
@@ -9277,7 +9694,7 @@ var Base = class {
9277
9694
  const target = targets?.find((target2) => target2.path === entry.path);
9278
9695
  if (nested)
9279
9696
  pending.push({
9280
- entries: (0, import_utils25.compact)((0, import_utils25.castArray)(nested)),
9697
+ entries: (0, import_utils26.compact)((0, import_utils26.castArray)(nested)),
9281
9698
  modelName: entry.model,
9282
9699
  configuration: target?.configuration,
9283
9700
  targets: target?.relatedTargets
@@ -9287,7 +9704,7 @@ var Base = class {
9287
9704
  }
9288
9705
  }
9289
9706
  getForeignKeyValues(value) {
9290
- return (0, import_utils25.flatten)((0, import_utils25.castArray)(value));
9707
+ return (0, import_utils26.flatten)((0, import_utils26.castArray)(value));
9291
9708
  }
9292
9709
  getForeignKey(value) {
9293
9710
  return String(value);
@@ -9295,7 +9712,7 @@ var Base = class {
9295
9712
  buildForeignKeyIndex(rows2, foreignField) {
9296
9713
  const index = /* @__PURE__ */ new Map();
9297
9714
  for (const row of rows2) {
9298
- for (const value of this.getForeignKeyValues((0, import_utils25.get)(row, foreignField))) {
9715
+ for (const value of this.getForeignKeyValues((0, import_utils26.get)(row, foreignField))) {
9299
9716
  const key = this.getForeignKey(value);
9300
9717
  const values = index.get(key);
9301
9718
  if (values) values.push(row);
@@ -9331,9 +9748,9 @@ var Base = class {
9331
9748
  async includeDocs(docs, include, parentAuthorization) {
9332
9749
  assertPublicAdmission(include, "include");
9333
9750
  if (!include) return docs;
9334
- const includes = (0, import_utils25.compact)((0, import_utils25.castArray)(include));
9751
+ const includes = (0, import_utils26.compact)((0, import_utils26.castArray)(include));
9335
9752
  if (includes.length === 0) return docs;
9336
- const isSingle = !(0, import_utils25.isArray)(docs);
9753
+ const isSingle = !(0, import_utils26.isArray)(docs);
9337
9754
  let docList = (isSingle ? [docs] : docs).map(prepareIncludeOutput);
9338
9755
  for (let x = 0; x < includes.length; x++) {
9339
9756
  const include2 = includes[x];
@@ -9363,7 +9780,7 @@ var Base = class {
9363
9780
  const svc = await this.getAuthorizedTargetService(model, "read", path, parentAuthorization);
9364
9781
  for (let y = 0; y < docs.length; y++) {
9365
9782
  const doc = docs[y];
9366
- const localValue = (0, import_utils25.get)(doc, localField);
9783
+ const localValue = (0, import_utils26.get)(doc, localField);
9367
9784
  const execution = this.relatedExecution(svc, include, parentAuthorization);
9368
9785
  const prepared = await prepareModelQuery(
9369
9786
  svc,
@@ -9398,15 +9815,15 @@ var Base = class {
9398
9815
  const { model, op, path, localField, foreignField, filter: _filters, args = {}, options = {} } = include;
9399
9816
  const svc = await this.getAuthorizedTargetService(model, op, path, parentAuthorization);
9400
9817
  const includeLocalValues = [];
9401
- (0, import_utils25.forEach)(docs, (doc) => {
9402
- includeLocalValues.push(...this.getForeignKeyValues((0, import_utils25.get)(doc, localField)));
9818
+ (0, import_utils26.forEach)(docs, (doc) => {
9819
+ includeLocalValues.push(...this.getForeignKeyValues((0, import_utils26.get)(doc, localField)));
9403
9820
  });
9404
9821
  const execution = this.relatedExecution(svc, include, parentAuthorization);
9405
9822
  const prepared = await prepareModelQuery(
9406
9823
  svc,
9407
9824
  execution,
9408
9825
  { kind: "client-read", filter: _filters ?? {} },
9409
- { [foreignField]: { $in: (0, import_utils25.flatten)(includeLocalValues) } },
9826
+ { [foreignField]: { $in: (0, import_utils26.flatten)(includeLocalValues) } },
9410
9827
  true
9411
9828
  );
9412
9829
  const trustedArgs = this.sanitizeIncludeArgs(args, "list");
@@ -9449,7 +9866,7 @@ var Base = class {
9449
9866
  }
9450
9867
  for (let y = 0; y < docs.length; y++) {
9451
9868
  const doc = docs[y];
9452
- const matches = this.getIndexedMatches(index, (0, import_utils25.get)(doc, localField));
9869
+ const matches = this.getIndexedMatches(index, (0, import_utils26.get)(doc, localField));
9453
9870
  const isolated = matches.map((m) => copyAuthorizedOutput(m));
9454
9871
  attachIncludeOutput(doc, path, op === "list" ? isolated : isolated[0]);
9455
9872
  }
@@ -9458,7 +9875,7 @@ var Base = class {
9458
9875
  async includeDocsCount(docs, include, parentAuthorization) {
9459
9876
  const { model, path, localField, foreignField, filter: _filters } = include;
9460
9877
  const svc = await this.getAuthorizedTargetService(model, "count", path, parentAuthorization);
9461
- const groups = prepareCountGroups(docs, (doc) => (0, import_utils25.get)(doc, localField));
9878
+ const groups = prepareCountGroups(docs, (doc) => (0, import_utils26.get)(doc, localField));
9462
9879
  const execution = this.relatedExecution(svc, include, parentAuthorization);
9463
9880
  const prepared = await prepareModelQuery(
9464
9881
  svc,
@@ -9512,7 +9929,7 @@ var Base = class {
9512
9929
  }
9513
9930
  const state = this.getCorrelatedExecState();
9514
9931
  docs = docs.map(prepareIncludeOutput);
9515
- const resolvedSnapshots = snapshots2 ?? docs.map((doc) => (0, import_utils25.cloneDeep)(toObject(getIncludeSource(doc))));
9932
+ const resolvedSnapshots = snapshots2 ?? docs.map((doc) => (0, import_utils26.cloneDeep)(toObject(getIncludeSource(doc))));
9516
9933
  for (const include of correlatedIncludes) {
9517
9934
  switch (include.op) {
9518
9935
  case "read":
@@ -9861,10 +10278,10 @@ var Base = class {
9861
10278
  }
9862
10279
  let ret = result2.data;
9863
10280
  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);
10281
+ 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
10282
  }
9866
10283
  if (sqOptions.compact) {
9867
- ret = (0, import_utils25.compact)((0, import_utils25.castArray)(ret));
10284
+ ret = (0, import_utils26.compact)((0, import_utils26.castArray)(ret));
9868
10285
  }
9869
10286
  return ret;
9870
10287
  }
@@ -9879,96 +10296,6 @@ var Base = class {
9879
10296
  var import_utils36 = require("@web-ts-toolkit/utils");
9880
10297
  var import_just_diff = require("just-diff");
9881
10298
 
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
10299
  // src/acl/distinct-field-authorization.ts
9973
10300
  var import_utils27 = require("@web-ts-toolkit/utils");
9974
10301
  init_field_authorization();
@@ -10106,6 +10433,7 @@ init_finalize_model_output();
10106
10433
  init_populate_target();
10107
10434
  init_virtual_populate_execution();
10108
10435
  init_request_work();
10436
+ init_populate_policy2();
10109
10437
  var populateExecutors = /* @__PURE__ */ new WeakMap();
10110
10438
  function registerSubdocumentPopulateExecutor(service, execute2, core) {
10111
10439
  populateExecutors.set(service, { execute: execute2, core });
@@ -10138,7 +10466,7 @@ function prepareSubdocumentOutput(service, sub, operation, virtualAccess, output
10138
10466
  service.getServiceModelName(),
10139
10467
  { populate },
10140
10468
  0,
10141
- configuration
10469
+ getCapturedPopulatePolicyDefaults(configuration)
10142
10470
  ),
10143
10471
  void 0,
10144
10472
  configuration,
@@ -11177,12 +11505,15 @@ var Service = class extends Base {
11177
11505
  model: this.model.mongooseModel,
11178
11506
  modelName: this.modelName
11179
11507
  }),
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 },
11508
+ configuration: () => {
11509
+ const populatePolicyDefaults = modelServicePopulatePolicyDefaults(this, this.requestRuntime);
11510
+ return this.requestRuntime.getModelInstance(this.modelName) ? captureModelAuthorizationConfiguration(
11511
+ this.requestRuntime,
11512
+ this.modelName,
11513
+ { ...this.options, defaults: this.defaults },
11514
+ populatePolicyDefaults
11515
+ ) : { catalog: { paths: [] }, ...this.options, populatePolicyDefaults };
11516
+ },
11186
11517
  permissions: () => this.requestCore.getPermissions?.() ?? new permission_default({}),
11187
11518
  parse: (filter2) => this.parseClientData(filter2, this.getCorrelatedExecState().scheduler),
11188
11519
  validate: (filter2, expanded) => {
@@ -11231,7 +11562,7 @@ var Service = class extends Base {
11231
11562
  });
11232
11563
  }
11233
11564
  get options() {
11234
- return modelServiceOptions(this, () => this.getModelRouterOptions(this.modelName));
11565
+ return modelServiceOptions(this, this.requestRuntime, () => this.getModelRouterOptions(this.modelName));
11235
11566
  }
11236
11567
  /**
11237
11568
  * Presentation/query defaults for this service instance; an explicit assignment
@@ -11716,14 +12047,14 @@ var Service = class extends Base {
11716
12047
  }
11717
12048
  });
11718
12049
  }
11719
- captureRelated(args, defaults) {
11720
- const globalOptions = modelServiceGlobalOptions(this, this.requestRuntime);
11721
- const effective = { populate: args?.populate ?? defaults?.populate, include: args?.include ?? defaults?.include };
12050
+ captureRelated(args, defaults2) {
12051
+ const populatePolicyDefaults = modelServicePopulatePolicyDefaults(this, this.requestRuntime);
12052
+ const effective = { populate: args?.populate ?? defaults2?.populate, include: args?.include ?? defaults2?.include };
11722
12053
  if (effective.include) {
11723
12054
  const processed = this.processInclude(effective.include);
11724
12055
  effective.include = [...processed.includes, ...processed.correlatedIncludes];
11725
12056
  }
11726
- return captureRelatedTargets(this.requestRuntime, this.modelName, effective, 0, globalOptions);
12057
+ return captureRelatedTargets(this.requestRuntime, this.modelName, effective, 0, populatePolicyDefaults);
11727
12058
  }
11728
12059
  /** Canonical population uses the target's retained policy for both fetch and output. */
11729
12060
  async genExecutionPopulate(execution, access, populate) {
@@ -11749,7 +12080,12 @@ var Service = class extends Base {
11749
12080
  const modelName = target?.modelName;
11750
12081
  if (!modelName) continue;
11751
12082
  const policy = relatedPolicy(state.authorization, state.binding, descriptor.path);
11752
- const svc = this.requestCore.getPublicService(modelName);
12083
+ const svc = withCapturedPopulateModel(
12084
+ this.requestRuntime,
12085
+ modelName,
12086
+ target.model,
12087
+ () => this.requestCore.getPublicService(modelName)
12088
+ );
11753
12089
  const child = createRelatedExecution(
11754
12090
  svc,
11755
12091
  {
@@ -11794,8 +12130,8 @@ var Service = class extends Base {
11794
12130
  snapshot: readServiceAuthorization(childState.authorization, childState.binding).configuration,
11795
12131
  fetchBinding: {
11796
12132
  runtime: this.requestRuntime,
11797
- model: childState.binding.model,
11798
- schema: childState.binding.model.schema,
12133
+ model: target.model,
12134
+ schema: target.model.schema,
11799
12135
  configuration: targetConfiguration,
11800
12136
  requestRead: targetAccess === "read" && policy?.operation.mode !== "grant" && readServiceAuthorization(childState.authorization, childState.binding).authorization.rows.mode === "request",
11801
12137
  staticObjectIdReference: captured.relatedTargets.find((target2) => target2.path === descriptor.path)?.staticObjectIdReference
@@ -14652,9 +14988,20 @@ var Core = class {
14652
14988
  if (!(0, import_utils40.isString)(p)) assertPopulateAccess(p.access);
14653
14989
  }
14654
14990
  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);
14991
+ const populatePolicyDefaults = modelServicePopulatePolicyDefaults(this, runtime);
14992
+ const relatedTargets = captureRelatedTargets(
14993
+ runtime,
14994
+ modelName,
14995
+ { populate: descriptors },
14996
+ 0,
14997
+ populatePolicyDefaults
14998
+ );
14999
+ const sourceConfiguration = captureModelAuthorizationConfiguration(
15000
+ runtime,
15001
+ modelName,
15002
+ void 0,
15003
+ populatePolicyDefaults
15004
+ );
14658
15005
  const originalPermissions = this.getGlobalPermissions();
14659
15006
  const permissions = new permission_default(
14660
15007
  Object.fromEntries(originalPermissions.keys.map((key) => [key, originalPermissions.has(key)]))
@@ -14751,7 +15098,15 @@ var Core = class {
14751
15098
  docPermissionsAccess: planAccess,
14752
15099
  requestedSelect: originalSelect,
14753
15100
  plan: targetPlan,
14754
- snapshot: targetSnapshot
15101
+ snapshot: targetSnapshot,
15102
+ fetchBinding: {
15103
+ runtime,
15104
+ model: target.model,
15105
+ schema: target.model.schema,
15106
+ configuration: targetConfiguration,
15107
+ requestRead: populateAccess === "read",
15108
+ staticObjectIdReference: target.staticObjectIdReference
15109
+ }
14755
15110
  });
14756
15111
  return ret;
14757
15112
  })