@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/advanced.mjs CHANGED
@@ -51,7 +51,7 @@ import JsonRouter from "@web-ts-toolkit/express-json-router";
51
51
  import { isPlainObject } from "@web-ts-toolkit/utils";
52
52
 
53
53
  // src/acl/unsafe-snapshot-options.ts
54
- var unsafeSnapshotOptions = [
54
+ var unsafeSnapshotCheckOptions = [
55
55
  "unsafeSkipListDocumentSnapshotChecks",
56
56
  "unsafeSkipReadDocumentSnapshotChecks",
57
57
  "unsafeSkipListOutputSnapshotChecks",
@@ -59,6 +59,11 @@ var unsafeSnapshotOptions = [
59
59
  "unsafeSkipListNestedDocumentSnapshotChecks",
60
60
  "unsafeSkipReadNestedDocumentSnapshotChecks"
61
61
  ];
62
+ var unsafeInitialOutputCopyOptions = [
63
+ "unsafeSkipListInitialOutputSnapshotCopy",
64
+ "unsafeSkipReadInitialOutputSnapshotCopy"
65
+ ];
66
+ var unsafeSnapshotOptions = [...unsafeSnapshotCheckOptions, ...unsafeInitialOutputCopyOptions];
62
67
 
63
68
  // src/validation/public-admission.ts
64
69
  var privateControls = [
@@ -126,9 +131,9 @@ function assertPublicAdmission(input, kind = "envelope") {
126
131
  for (const key of ["filter", "match", "data"]) add(record2[key], "data", key);
127
132
  }
128
133
  }
129
- function assertHydrationDefaults(defaults) {
130
- if (defaults && typeof defaults === "object") {
131
- const record2 = defaults;
134
+ function assertHydrationDefaults(defaults2) {
135
+ if (defaults2 && typeof defaults2 === "object") {
136
+ const record2 = defaults2;
132
137
  if ("hydration" in record2)
133
138
  throw new TypeError("defaults.hydration is unsupported; use model hydration configuration");
134
139
  for (const bucket of [
@@ -156,11 +161,11 @@ function assertHydrationDefaults(defaults) {
156
161
  }
157
162
  }
158
163
  }
159
- function assertPublicDefaults(defaults) {
160
- assertHydrationDefaults(defaults);
161
- assertPublicAdmission(defaults);
162
- if (defaults && typeof defaults === "object") {
163
- for (const value of Object.values(defaults)) assertPublicAdmission(value);
164
+ function assertPublicDefaults(defaults2) {
165
+ assertHydrationDefaults(defaults2);
166
+ assertPublicAdmission(defaults2);
167
+ if (defaults2 && typeof defaults2 === "object") {
168
+ for (const value of Object.values(defaults2)) assertPublicAdmission(value);
164
169
  }
165
170
  }
166
171
  var requestAuthorization = Object.freeze({ outputFields: Object.freeze({ mode: "request" }) });
@@ -190,6 +195,32 @@ function normalizeHydrationUpdate(current, key, value) {
190
195
  return normalizeHydration({ ...normalizeHydration(current), [method]: value });
191
196
  }
192
197
 
198
+ // src/options/populate-policy.ts
199
+ var populatePolicyKeys = [
200
+ "requireOperationAccessForPopulateQueries",
201
+ "requireOperationAccessForPopulateDependencies"
202
+ ];
203
+ function isPopulatePolicyKey(key) {
204
+ return populatePolicyKeys.includes(key);
205
+ }
206
+ function normalizePopulatePolicyValue(value) {
207
+ return value === void 0 ? void 0 : value !== false;
208
+ }
209
+ function normalizePopulatePolicyOptions(options) {
210
+ const next = { ...options };
211
+ for (const key of populatePolicyKeys) {
212
+ if (key in options)
213
+ next[key] = normalizePopulatePolicyValue(options[key]);
214
+ }
215
+ return next;
216
+ }
217
+ function assertNoGlobalPopulatePolicy(key) {
218
+ if (isPopulatePolicyKey(key))
219
+ throw new TypeError(
220
+ `${key} is target-model configuration; migrate to setModelOptions(targetModelName, { ${key}: value }) or setDefaultModelOptions({ ${key}: value }) for runtime model defaults`
221
+ );
222
+ }
223
+
193
224
  // src/runtime.ts
194
225
  import mschema2Jsonschema from "mongoose-schema-jsonschema";
195
226
  import {
@@ -696,6 +727,7 @@ var freezeConfigValue = (value) => {
696
727
  return value;
697
728
  };
698
729
  var cloneAndFreezeForStore = (value) => freezeConfigValue(cloneForRead(value));
730
+ var cloneOptionsSnapshot = (value) => freezeConfigValue(cloneForRead(value));
699
731
  var getNestedOption = (manager, key, defaultValue) => resolveNestedOption((path, fallback) => manager.get(path, fallback), String(key), defaultValue);
700
732
  var resolveNestedOption = (read, key, defaultValue) => {
701
733
  const keys2 = key.split(".");
@@ -1185,7 +1217,8 @@ function resolveSnapshotDescriptor(scopeVirtuals, virtualName, access) {
1185
1217
  import { get as get2, isPlainObject as isPlainObject12 } from "@web-ts-toolkit/utils";
1186
1218
 
1187
1219
  // src/acl/authorization-snapshot.ts
1188
- import { isDeepStrictEqual } from "util";
1220
+ import { isDeepStrictEqual, types as types2 } from "util";
1221
+ import { Buffer as NodeBuffer } from "buffer";
1189
1222
  import { mongo } from "mongoose";
1190
1223
  import JsonRouter2 from "@web-ts-toolkit/express-json-router";
1191
1224
  var ServiceAuthorizationError = class extends JsonRouter2.clientErrors.BadRequestError {
@@ -1244,6 +1277,7 @@ function copyAuthorizationValue(value, configuration = false) {
1244
1277
  if (array && input.length > 2e4) authorizationError("snapshot array exceeds structural limits");
1245
1278
  if (!array) authorizationRecord(input, "snapshot");
1246
1279
  const result = array ? [] : {};
1280
+ let definedProperty = false;
1247
1281
  for (const key of Reflect.ownKeys(input)) {
1248
1282
  if (array && key === "length") continue;
1249
1283
  if (typeof key !== "string" || unsafeKeys.has(key)) authorizationError("unsafe snapshot key");
@@ -1251,12 +1285,16 @@ function copyAuthorizationValue(value, configuration = false) {
1251
1285
  const descriptor = Object.getOwnPropertyDescriptor(input, key);
1252
1286
  if (!("value" in descriptor) || !descriptor.enumerable && configuration !== "document")
1253
1287
  authorizationError("accessor/non-enumerable input");
1254
- Object.defineProperty(result, key, {
1255
- value: copy(descriptor.value, depth + 1),
1256
- enumerable: true,
1257
- writable: true,
1258
- configurable: true
1259
- });
1288
+ const value2 = copy(descriptor.value, depth + 1);
1289
+ if (array || definedProperty && Object.getPrototypeOf(result) !== Object.prototype || key in result) {
1290
+ definedProperty = true;
1291
+ Object.defineProperty(result, key, {
1292
+ value: value2,
1293
+ enumerable: true,
1294
+ writable: true,
1295
+ configurable: true
1296
+ });
1297
+ } else result[key] = value2;
1260
1298
  }
1261
1299
  if (array) result.length = input.length;
1262
1300
  return Object.freeze(result);
@@ -1268,6 +1306,7 @@ function copyAuthorizationValue(value, configuration = false) {
1268
1306
  }
1269
1307
 
1270
1308
  // src/acl/field-catalog.ts
1309
+ import { types as types3 } from "util";
1271
1310
  var 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);
1272
1311
  var isSafeOutputPath = (path) => path.split(".").every(safeSegment);
1273
1312
  var inputControlSegments = /* @__PURE__ */ new Set([
@@ -1292,6 +1331,9 @@ function isSafeInputPath(path, requestIdentity = false) {
1292
1331
  return isSafeOutputPath(path) && path.split(".").every((part) => !inputControlSegments.has(part) && (requestIdentity || part !== "_id"));
1293
1332
  }
1294
1333
  function matchesCatalogPattern(pattern, path, descendants = false) {
1334
+ if (typeof pattern === "string" && typeof path === "string" && !pattern.includes("$*")) {
1335
+ return pattern === path || !!descendants && path.startsWith(pattern) && path[pattern.length] === ".";
1336
+ }
1295
1337
  const expected = pattern.split(".");
1296
1338
  const actual = path.split(".");
1297
1339
  return (descendants ? actual.length >= expected.length : actual.length === expected.length) && expected.every((part, index) => part === "$*" || part === actual[index]);
@@ -1392,7 +1434,16 @@ function captureAuthorizationFieldCatalog(schema, virtuals, documentPermissionFi
1392
1434
 
1393
1435
  // src/acl/populate-target-configuration.ts
1394
1436
  import { isPlainObject as isPlainObject11 } from "@web-ts-toolkit/utils";
1395
- function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions) {
1437
+
1438
+ // src/runtime-context.ts
1439
+ import { AsyncLocalStorage } from "async_hooks";
1440
+ var runtimeStorage = new AsyncLocalStorage();
1441
+ function getActiveRuntime() {
1442
+ return runtimeStorage.getStore() ?? null;
1443
+ }
1444
+
1445
+ // src/acl/populate-target-configuration.ts
1446
+ function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions, defaults2 = runtime.getDefaultModelOptions()) {
1396
1447
  const label = `Populate target "${modelName}" for ${source}`;
1397
1448
  if (!proposedOptions && !runtime.hasModel(modelName))
1398
1449
  authorizationError(
@@ -1401,7 +1452,7 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
1401
1452
  const model = runtime.getModelInstance(modelName);
1402
1453
  if (!model) authorizationError(`${label} requires an actual registered Mongoose model in this runtime`);
1403
1454
  const options = proposedOptions ?? runtime.getModelOptions(modelName);
1404
- const permissionSchema = options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema;
1455
+ const permissionSchema = options.permissionSchema === void 0 ? defaults2.permissionSchema : options.permissionSchema;
1405
1456
  if (!isPlainObject11(permissionSchema))
1406
1457
  authorizationError(
1407
1458
  `${label} requires an effective object permissionSchema; configure the model or runtime model defaults ({} explicitly closes business fields)`
@@ -1409,6 +1460,31 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
1409
1460
  return { model, options: { ...options, permissionSchema } };
1410
1461
  }
1411
1462
 
1463
+ // src/acl/populate-policy.ts
1464
+ var defaults = /* @__PURE__ */ new WeakMap();
1465
+ function capturePopulatePolicyDefaults(runtime) {
1466
+ const options = runtime.getDefaultModelOptions();
1467
+ const token = () => {
1468
+ };
1469
+ defaults.set(
1470
+ token,
1471
+ Object.freeze({
1472
+ requireOperationAccessForPopulateQueries: options.requireOperationAccessForPopulateQueries !== false,
1473
+ requireOperationAccessForPopulateDependencies: options.requireOperationAccessForPopulateDependencies !== false
1474
+ })
1475
+ );
1476
+ return token;
1477
+ }
1478
+ function resolvePopulatePolicy(options, token) {
1479
+ const captured = defaults.get(token);
1480
+ if (!captured) return authorizationError("invalid captured populate model defaults");
1481
+ const resolve = (key) => (options[key] === void 0 ? captured[key] : options[key]) !== false;
1482
+ return Object.freeze({
1483
+ requireOperationAccessForPopulateQueries: resolve(populatePolicyKeys[0]),
1484
+ requireOperationAccessForPopulateDependencies: resolve(populatePolicyKeys[1])
1485
+ });
1486
+ }
1487
+
1412
1488
  // src/acl/virtual-populate-dependencies.ts
1413
1489
  var elementType = (type) => type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
1414
1490
  var join = (prefix, path) => prefix ? `${prefix}.${path}` : path;
@@ -1508,9 +1584,7 @@ function normalizeSelection(select, catalog, label) {
1508
1584
  includeId: selection.includes("_id")
1509
1585
  };
1510
1586
  }
1511
- function captureVirtualPopulateDependencies(runtime, modelName, options, globalOptions = runtime.getGlobalOptions()) {
1512
- const requireOperationAccessForPopulateDependencies = globalOptions.requireOperationAccessForPopulateDependencies !== false;
1513
- const requireOperationAccessForPopulateQueries = globalOptions.requireOperationAccessForPopulateQueries !== false;
1587
+ function captureVirtualPopulateDependencies(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime), proposed) {
1514
1588
  const model = runtime.getModelInstance(modelName);
1515
1589
  const targets = /* @__PURE__ */ new Map();
1516
1590
  const scopes = [];
@@ -1554,18 +1628,19 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, globalO
1554
1628
  runtime,
1555
1629
  ref,
1556
1630
  `dependsOnPopulate virtual "${label}"`,
1557
- ref === modelName ? options : void 0
1631
+ ref === modelName ? options : proposed?.models.get(ref),
1632
+ proposed?.defaults
1558
1633
  );
1559
- const defaults = runtime.getDefaultModelOptions();
1560
- const readOption = (key) => resolveNestedOption((path2, fallback) => get2(targetOptions, path2, fallback), key, get2(defaults, key));
1561
- const documentPermissionField = targetOptions.documentPermissionField ?? defaults.documentPermissionField;
1634
+ const defaults2 = proposed?.defaults ?? runtime.getDefaultModelOptions();
1635
+ const readOption = (key) => resolveNestedOption((path2, fallback) => get2(targetOptions, path2, fallback), key, get2(defaults2, key));
1636
+ const documentPermissionField = targetOptions.documentPermissionField ?? defaults2.documentPermissionField;
1562
1637
  const catalog = captureAuthorizationFieldCatalog(targetModel.schema, void 0, documentPermissionField);
1563
1638
  const configuration = copyAuthorizationValue(
1564
1639
  {
1565
1640
  catalog,
1566
1641
  documentPermissionField,
1567
- requireOperationAccessForPopulateDependencies,
1568
- requireOperationAccessForPopulateQueries,
1642
+ populatePolicyDefaults,
1643
+ ...resolvePopulatePolicy(targetOptions, populatePolicyDefaults),
1569
1644
  permissionSchema: targetOptions.permissionSchema,
1570
1645
  operationAccess: { read: readOption("operationAccess.read") },
1571
1646
  baseFilter: { read: readOption("baseFilter.read") },
@@ -1660,6 +1735,15 @@ var defaultModelOptions = {
1660
1735
  basePath: null,
1661
1736
  alwaysSelectFields: []
1662
1737
  };
1738
+ var modelOverrides = (options) => {
1739
+ const result = Object.fromEntries(
1740
+ Object.entries(options).filter(
1741
+ ([key, value]) => value !== void 0 || key === "operationAccess" || isPopulatePolicyKey(key)
1742
+ )
1743
+ );
1744
+ for (const key of unsafeSnapshotOptions) if (key in result) result[key] = result[key] === true;
1745
+ return cloneOptionsSnapshot(result);
1746
+ };
1663
1747
  var defaultDataOptions = {
1664
1748
  basePath: null,
1665
1749
  parentPath: "/",
@@ -1793,12 +1877,12 @@ var getNestedChildFields = (parentSchema, fieldName) => {
1793
1877
  }
1794
1878
  return fields;
1795
1879
  };
1796
- var cloneVirtualsForValidation = (value) => {
1797
- if (Array.isArray(value)) return value.map((item) => cloneVirtualsForValidation(item));
1880
+ var cloneModelOptionForUpdate = (value) => {
1881
+ if (Array.isArray(value)) return value.map((item) => cloneModelOptionForUpdate(item));
1798
1882
  if (!value || typeof value !== "object") return value;
1799
1883
  if (Object.getPrototypeOf(value) !== Object.prototype) return value;
1800
1884
  return Object.fromEntries(
1801
- Object.entries(value).map(([k, v]) => [k, cloneVirtualsForValidation(v)])
1885
+ Object.entries(value).map(([k, v]) => [k, cloneModelOptionForUpdate(v)])
1802
1886
  );
1803
1887
  };
1804
1888
  var validateVirtualDependsOn = (dependsOn, entryLabel, storedFields, siblingVirtualNames) => {
@@ -1994,8 +2078,6 @@ var AccessRuntime = class {
1994
2078
  {
1995
2079
  requestPermissionField: "_permissions",
1996
2080
  globalPermissions: () => ({}),
1997
- requireOperationAccessForPopulateQueries: true,
1998
- requireOperationAccessForPopulateDependencies: true,
1999
2081
  logger: defaultLogger,
2000
2082
  requestComplexity: defaultRequestComplexity
2001
2083
  },
@@ -2010,15 +2092,20 @@ var AccessRuntime = class {
2010
2092
  queryRouteSegment: "__query",
2011
2093
  mutationRouteSegment: "__mutation",
2012
2094
  operationAccess: false,
2095
+ requireOperationAccessForPopulateQueries: true,
2096
+ requireOperationAccessForPopulateDependencies: true,
2013
2097
  modelPermissionPrefix: "",
2014
2098
  unsafeSkipListDocumentSnapshotChecks: false,
2015
2099
  unsafeSkipReadDocumentSnapshotChecks: false,
2016
2100
  unsafeSkipListOutputSnapshotChecks: false,
2017
2101
  unsafeSkipReadOutputSnapshotChecks: false,
2018
2102
  unsafeSkipListNestedDocumentSnapshotChecks: false,
2019
- unsafeSkipReadNestedDocumentSnapshotChecks: false
2103
+ unsafeSkipReadNestedDocumentSnapshotChecks: false,
2104
+ unsafeSkipListInitialOutputSnapshotCopy: false,
2105
+ unsafeSkipReadInitialOutputSnapshotCopy: false
2020
2106
  }).build();
2021
2107
  this.modelOptions = {};
2108
+ this.modelOptionOverrides = {};
2022
2109
  this.modelJsonSchemas = {};
2023
2110
  this.dataOptions = {};
2024
2111
  this.modelRefs = {};
@@ -2106,6 +2193,7 @@ var AccessRuntime = class {
2106
2193
  globalOptions: this.globalOptions.snapshot(),
2107
2194
  defaultModelOptions: this.defaultModelOptions.snapshot(),
2108
2195
  modelOptions: modelOptionsSnap,
2196
+ modelOptionOverrides: { ...this.modelOptionOverrides },
2109
2197
  dataOptions: dataOptionsSnap,
2110
2198
  modelInstances: { ...this.modelInstances },
2111
2199
  modelJsonSchemas: { ...this.modelJsonSchemas },
@@ -2120,6 +2208,10 @@ var AccessRuntime = class {
2120
2208
  restoreBootstrapSnapshot(snapshot) {
2121
2209
  this.globalOptions.restore(snapshot.globalOptions);
2122
2210
  this.defaultModelOptions.restore(snapshot.defaultModelOptions);
2211
+ for (const name of Object.keys(this.modelOptionOverrides)) delete this.modelOptionOverrides[name];
2212
+ for (const [name, options] of Object.entries(snapshot.modelOptionOverrides)) {
2213
+ this.modelOptionOverrides[name] = modelOverrides(options);
2214
+ }
2123
2215
  for (const name of Object.keys(this.modelOptions)) {
2124
2216
  if (!(name in snapshot.modelOptions)) {
2125
2217
  delete this.modelOptions[name];
@@ -2130,8 +2222,7 @@ var AccessRuntime = class {
2130
2222
  if (existing) {
2131
2223
  existing.restore(opts);
2132
2224
  } else {
2133
- const mgr = this.createModelOptions(name);
2134
- mgr.restore(opts);
2225
+ const mgr = this.createModelOptions(name, opts);
2135
2226
  this.modelOptions[name] = mgr;
2136
2227
  }
2137
2228
  }
@@ -2174,18 +2265,11 @@ var AccessRuntime = class {
2174
2265
  }
2175
2266
  /** Shallowly replace supplied global values; nested objects such as requestComplexity are not deep-merged. */
2176
2267
  setGlobalOptions(options) {
2177
- const next = { ...options };
2178
- if ("requireOperationAccessForPopulateQueries" in next)
2179
- next.requireOperationAccessForPopulateQueries = next.requireOperationAccessForPopulateQueries !== false;
2180
- if ("requireOperationAccessForPopulateDependencies" in next)
2181
- next.requireOperationAccessForPopulateDependencies = next.requireOperationAccessForPopulateDependencies !== false;
2182
- this.globalOptions.assign(next);
2268
+ for (const key of populatePolicyKeys) if (key in options) assertNoGlobalPopulatePolicy(key);
2269
+ this.globalOptions.assign({ ...options });
2183
2270
  }
2184
2271
  setGlobalOption(key, value) {
2185
- if (key === "requireOperationAccessForPopulateQueries" || key === "requireOperationAccessForPopulateDependencies") {
2186
- this.globalOptions.set(key, value !== false);
2187
- return;
2188
- }
2272
+ assertNoGlobalPopulatePolicy(String(key));
2189
2273
  this.globalOptions.set(key, value);
2190
2274
  }
2191
2275
  getGlobalOptions() {
@@ -2194,28 +2278,30 @@ var AccessRuntime = class {
2194
2278
  getGlobalOption(key, defaultValue) {
2195
2279
  return this.globalOptions.get(key, defaultValue);
2196
2280
  }
2197
- /** Update model starting defaults shallowly; already-stored model values are not broadcast-replaced. */
2281
+ /** Update inherited model defaults shallowly. Explicit model values and captured calls are unchanged. */
2198
2282
  setDefaultModelOptions(options) {
2199
2283
  assertPublicDefaults(options.defaults);
2200
2284
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
2201
- this.defaultModelOptions.assign(options);
2285
+ const draft = new OptionsManager(
2286
+ this.getDefaultModelOptions()
2287
+ ).build();
2288
+ draft.assign(normalizePopulatePolicyOptions(options));
2289
+ this.publishDefaultModelOptions(draft.fetch());
2202
2290
  }
2203
2291
  setDefaultModelOption(key, value) {
2204
2292
  const keyStr = String(key);
2205
- if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
2206
- this.defaultModelOptions.set(
2207
- "hydration",
2208
- normalizeHydrationUpdate(this.getDefaultModelOptions().hydration, keyStr, value)
2209
- );
2210
- return;
2211
- }
2212
- if (keyStr === "defaults") assertPublicDefaults(value);
2213
- else if (keyStr.startsWith("defaults.")) {
2214
- const proposed = {};
2215
- set3(proposed, keyStr.slice("defaults.".length), value);
2216
- assertPublicDefaults(proposed);
2293
+ const draft = new OptionsManager(
2294
+ this.getDefaultModelOptions()
2295
+ ).build();
2296
+ if (isPopulatePolicyKey(keyStr)) {
2297
+ draft.set(keyStr, normalizePopulatePolicyValue(value));
2298
+ } else if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
2299
+ draft.set("hydration", normalizeHydrationUpdate(this.getDefaultModelOptions().hydration, keyStr, value));
2300
+ } else {
2301
+ draft.set(key, value);
2217
2302
  }
2218
- this.defaultModelOptions.set(key, value);
2303
+ assertPublicDefaults(draft.fetch().defaults);
2304
+ this.publishDefaultModelOptions(draft.fetch());
2219
2305
  }
2220
2306
  getDefaultModelOptions() {
2221
2307
  return this.defaultModelOptions.fetch();
@@ -2223,30 +2309,103 @@ var AccessRuntime = class {
2223
2309
  getDefaultModelOption(key, defaultValue) {
2224
2310
  return this.defaultModelOptions.get(key, defaultValue);
2225
2311
  }
2226
- createModelOptions(modelName) {
2312
+ resolveModelOptions(modelName, overrides = this.modelOptionOverrides[modelName] ?? {}, defaults2 = this.getDefaultModelOptions()) {
2313
+ const inherited = { ...defaults2 };
2314
+ for (const key of populatePolicyKeys) delete inherited[key];
2315
+ const effective = { ...defaultModelOptions, ...inherited, ...overrides, modelName };
2316
+ effective.basePath = normalizeBasePath(modelName, effective.basePath);
2317
+ for (const key of unsafeSnapshotOptions) effective[key] = effective[key] === true;
2318
+ refreshPermissionMetadata(effective);
2319
+ return cloneOptionsSnapshot(effective);
2320
+ }
2321
+ validateModelOptions(modelName, options, proposed) {
2322
+ validateVirtualsTree(
2323
+ this.getModelInstance(modelName),
2324
+ options.virtuals,
2325
+ options.documentPermissionField ?? "_permissions",
2326
+ modelName
2327
+ );
2328
+ captureVirtualPopulateDependencies(this, modelName, options, void 0, proposed);
2329
+ }
2330
+ publishDefaultModelOptions(options) {
2331
+ const next = { ...options };
2332
+ for (const key of unsafeSnapshotOptions) if (key in next) next[key] = next[key] === true;
2333
+ const defaults2 = cloneOptionsSnapshot(next);
2334
+ const models = new Map(
2335
+ Object.keys(this.modelOptions).map((name) => [name, this.resolveModelOptions(name, void 0, defaults2)])
2336
+ );
2337
+ for (const [name, options2] of models) this.validateModelOptions(name, options2, { defaults: defaults2, models });
2338
+ this.deferSnapshotWarnings(() => {
2339
+ this.defaultModelOptions.restore(defaults2);
2340
+ for (const [name, options2] of models) this.modelOptions[name].restore(options2);
2341
+ });
2342
+ }
2343
+ warnSnapshotFlag(modelName, key) {
2344
+ if (this.pendingSnapshotWarnings) {
2345
+ this.pendingSnapshotWarnings.push({ modelName, key });
2346
+ return;
2347
+ }
2348
+ const operation = key.startsWith("unsafeSkipRead") ? "read" : "list";
2349
+ const category = key.includes("NestedDocument") ? "nested-document" : key.includes("Output") ? "output" : "document";
2350
+ const risk = category === "output" ? "output mutation" : "source mutation";
2351
+ try {
2352
+ this.getGlobalOption("logger")?.warn?.(
2353
+ `UNSAFE: ${operation} ${category} snapshot checks disabled; ${risk} can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
2354
+ { modelName }
2355
+ );
2356
+ } catch {
2357
+ }
2358
+ }
2359
+ deferSnapshotWarnings(publish) {
2360
+ if (this.pendingSnapshotWarnings) return publish();
2361
+ const copyModes = this.initialOutputCopyModes();
2362
+ const pending = [];
2363
+ this.pendingSnapshotWarnings = pending;
2364
+ let result;
2365
+ try {
2366
+ result = publish();
2367
+ } finally {
2368
+ this.pendingSnapshotWarnings = void 0;
2369
+ }
2370
+ const nextCopyModes = this.initialOutputCopyModes();
2371
+ for (const { modelName, key } of pending) this.warnSnapshotFlag(modelName, key);
2372
+ for (const [modelName, modes] of nextCopyModes) {
2373
+ for (const operation of ["List", "Read"]) {
2374
+ const mode = modes[operation];
2375
+ if (mode === "off" || mode === copyModes.get(modelName)?.[operation]) continue;
2376
+ const key = `unsafeSkip${operation}InitialOutputSnapshotCopy`;
2377
+ const prerequisite = `unsafeSkip${operation}OutputSnapshotChecks`;
2378
+ try {
2379
+ this.getGlobalOption("logger")?.warn?.(
2380
+ 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.`,
2381
+ { modelName }
2382
+ );
2383
+ } catch {
2384
+ }
2385
+ }
2386
+ }
2387
+ return result;
2388
+ }
2389
+ initialOutputCopyModes() {
2390
+ return new Map(
2391
+ Object.entries(this.modelOptions).map(([modelName, options]) => {
2392
+ const mode = (operation) => options.get(`unsafeSkip${operation}InitialOutputSnapshotCopy`) !== true ? "off" : options.get(`unsafeSkip${operation}OutputSnapshotChecks`) === true ? "active" : "dormant";
2393
+ return [modelName, { List: mode("List"), Read: mode("Read") }];
2394
+ })
2395
+ );
2396
+ }
2397
+ createModelOptions(modelName, options = this.resolveModelOptions(modelName)) {
2227
2398
  const model = this.getModelInstance(modelName);
2228
2399
  if (!model) {
2229
2400
  throw new Error(
2230
2401
  `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this isolated runtime.`
2231
2402
  );
2232
2403
  }
2233
- const manager = new OptionsManager({
2234
- ...defaultModelOptions,
2235
- modelName
2236
- });
2404
+ const manager = new OptionsManager(options);
2237
2405
  const snapshotFlagChanged = (newValue, key, target, oldValue) => {
2238
2406
  target[key] = newValue === true;
2239
2407
  if (newValue !== true || oldValue === true) return;
2240
- const operation = key.startsWith("unsafeSkipRead") ? "read" : "list";
2241
- const category = key.includes("NestedDocument") ? "nested-document" : key.includes("Output") ? "output" : "document";
2242
- const risk = category === "output" ? "output mutation" : "source mutation";
2243
- try {
2244
- this.getGlobalOption("logger")?.warn?.(
2245
- `UNSAFE: ${operation} ${category} snapshot checks disabled; ${risk} can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
2246
- { modelName }
2247
- );
2248
- } catch {
2249
- }
2408
+ this.warnSnapshotFlag(modelName, key);
2250
2409
  };
2251
2410
  manager.onchange("permissionSchema", function(_newval, _key, target) {
2252
2411
  refreshPermissionMetadata(target);
@@ -2264,13 +2423,17 @@ var AccessRuntime = class {
2264
2423
  getOrCreateModelOptions(modelName) {
2265
2424
  let manager = this.modelOptions[modelName];
2266
2425
  if (!manager) {
2267
- manager = this.createModelOptions(modelName);
2268
- this.modelOptions[modelName] = manager;
2426
+ manager = this.deferSnapshotWarnings(() => {
2427
+ const created = this.createModelOptions(modelName);
2428
+ this.modelOptions[modelName] = created;
2429
+ return created;
2430
+ });
2269
2431
  }
2270
2432
  return manager;
2271
2433
  }
2272
2434
  /**
2273
- * Assign `{ ...modelDefaults, ...storedOptions, ...options }` shallowly. A supplied
2435
+ * Update explicit model overrides shallowly; undefined restores default inheritance
2436
+ * (operationAccess preserves its existing exact-key-only default fallback). A supplied
2274
2437
  * operationAccess/defaults object replaces that whole value. Defaults accept only
2275
2438
  * query/presentation settings; virtual configuration is validated before assignment.
2276
2439
  * Existing router.options remains its construction-time snapshot. Fresh model-service
@@ -2278,22 +2441,23 @@ var AccessRuntime = class {
2278
2441
  */
2279
2442
  setModelOptions(modelName, options) {
2280
2443
  assertPublicDefaults(options.defaults);
2444
+ options = normalizePopulatePolicyOptions(options);
2281
2445
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
2282
- const defaultOptions = this.getDefaultModelOptions();
2283
- const currentModelOptions = this.modelOptions[modelName]?.fetch() ?? { ...defaultModelOptions, modelName };
2284
- const merged = { ...defaultOptions, ...currentModelOptions, ...options };
2285
- const model = this.getModelInstance(modelName);
2286
- const permissionField = merged.documentPermissionField ?? currentModelOptions.documentPermissionField ?? this.getDefaultModelOption("documentPermissionField") ?? "_permissions";
2287
- validateVirtualsTree(model, merged.virtuals, permissionField, modelName);
2288
- captureVirtualPopulateDependencies(this, modelName, merged);
2289
- const manager = this.getOrCreateModelOptions(modelName);
2290
- manager.assign({ ...defaultOptions, ...currentModelOptions, ...options });
2446
+ const overrides = modelOverrides({ ...this.modelOptionOverrides[modelName], ...options });
2447
+ const effective = this.resolveModelOptions(modelName, overrides);
2448
+ this.validateModelOptions(modelName, effective);
2449
+ this.deferSnapshotWarnings(() => {
2450
+ const manager = this.modelOptions[modelName];
2451
+ if (manager) manager.restore(effective);
2452
+ else this.modelOptions[modelName] = this.createModelOptions(modelName, effective);
2453
+ this.modelOptionOverrides[modelName] = overrides;
2454
+ });
2291
2455
  }
2292
2456
  setModelOption(modelName, key, value) {
2293
2457
  const keyStr = String(key);
2294
2458
  if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
2295
- const hydration = normalizeHydrationUpdate(this.modelOptions[modelName]?.get("hydration"), keyStr, value);
2296
- this.getOrCreateModelOptions(modelName).set("hydration", hydration);
2459
+ const hydration = normalizeHydrationUpdate(this.resolveModelOptions(modelName).hydration, keyStr, value);
2460
+ this.setModelOptions(modelName, { hydration });
2297
2461
  return;
2298
2462
  }
2299
2463
  if (keyStr === "defaults") assertPublicDefaults(value);
@@ -2302,47 +2466,20 @@ var AccessRuntime = class {
2302
2466
  set3(proposed, keyStr.slice("defaults.".length), value);
2303
2467
  assertPublicDefaults(proposed);
2304
2468
  }
2305
- const manager = this.modelOptions[modelName];
2306
- if (keyStr === "virtuals" || keyStr.startsWith("virtuals.") || keyStr === "documentPermissionField") {
2307
- const model = this.getModelInstance(modelName);
2308
- const currentVirtuals = manager?.get("virtuals");
2309
- const currentPermissionField = manager?.get("documentPermissionField") ?? this.getDefaultModelOption("documentPermissionField") ?? "_permissions";
2310
- let proposedVirtuals = currentVirtuals;
2311
- let proposedPermissionField = currentPermissionField;
2312
- if (keyStr === "documentPermissionField") {
2313
- proposedPermissionField = value;
2314
- } else if (keyStr === "virtuals") {
2315
- proposedVirtuals = value;
2316
- } else {
2317
- const cloned = cloneVirtualsForValidation(currentVirtuals ?? {});
2318
- const nestedPath = keyStr.slice("virtuals.".length);
2319
- if (value === void 0) {
2320
- const segments = nestedPath.split(".");
2321
- let cursor = cloned;
2322
- for (let i = 0; i < segments.length - 1; i++) {
2323
- if (!isPlainObject13(cursor)) break;
2324
- cursor = cursor[segments[i]];
2325
- }
2326
- if (isPlainObject13(cursor)) {
2327
- delete cursor[segments[segments.length - 1]];
2328
- }
2329
- proposedVirtuals = cloned;
2330
- } else {
2331
- set3(cloned, nestedPath, value);
2332
- proposedVirtuals = cloned;
2333
- }
2334
- }
2335
- validateVirtualsTree(model, proposedVirtuals, proposedPermissionField, modelName);
2336
- captureVirtualPopulateDependencies(this, modelName, {
2337
- ...this.getDefaultModelOptions(),
2338
- ...manager?.fetch(),
2339
- virtuals: proposedVirtuals,
2340
- documentPermissionField: proposedPermissionField
2341
- });
2469
+ const [root, ...path] = keyStr.split(".");
2470
+ if (!path.length) {
2471
+ this.setModelOptions(modelName, { [root]: value });
2472
+ return;
2342
2473
  }
2343
- this.getOrCreateModelOptions(modelName).set(key, value);
2474
+ const current = this.resolveModelOptions(modelName);
2475
+ const nested = cloneModelOptionForUpdate(isPlainObject13(current[root]) ? current[root] : {});
2476
+ if (root === "virtuals" && value === void 0) {
2477
+ const parent = path.length === 1 ? nested : get3(nested, path.slice(0, -1));
2478
+ if (isPlainObject13(parent)) delete parent[path[path.length - 1]];
2479
+ } else set3(nested, path, value);
2480
+ this.setModelOptions(modelName, { [root]: nested });
2344
2481
  }
2345
- /** Frozen stored snapshot, not fully resolved per-path defaults. Read again for current configuration. */
2482
+ /** Frozen model/default snapshot; populate flags remain raw overrides. Read again for current values. */
2346
2483
  getModelOptions(modelName) {
2347
2484
  const manager = this.getOrCreateModelOptions(modelName);
2348
2485
  return manager.fetch();
@@ -2507,13 +2644,6 @@ var AccessRuntime = class {
2507
2644
  };
2508
2645
  var defaultRuntime = new AccessRuntime({ allowGlobalModelLookup: true });
2509
2646
 
2510
- // src/runtime-context.ts
2511
- import { AsyncLocalStorage } from "async_hooks";
2512
- var runtimeStorage = new AsyncLocalStorage();
2513
- function getActiveRuntime() {
2514
- return runtimeStorage.getStore() ?? null;
2515
- }
2516
-
2517
2647
  // src/options/global-options.ts
2518
2648
  var getRuntime = () => getActiveRuntime() ?? defaultRuntime;
2519
2649
  var getGlobalOption = (key, defaultValue) => {