@web-ts-toolkit/access-router 0.61.0 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 {
@@ -1292,6 +1325,9 @@ function isSafeInputPath(path, requestIdentity = false) {
1292
1325
  return isSafeOutputPath(path) && path.split(".").every((part) => !inputControlSegments.has(part) && (requestIdentity || part !== "_id"));
1293
1326
  }
1294
1327
  function matchesCatalogPattern(pattern, path, descendants = false) {
1328
+ if (typeof pattern === "string" && typeof path === "string" && !pattern.includes("$*")) {
1329
+ return pattern === path || !!descendants && path.startsWith(pattern) && path[pattern.length] === ".";
1330
+ }
1295
1331
  const expected = pattern.split(".");
1296
1332
  const actual = path.split(".");
1297
1333
  return (descendants ? actual.length >= expected.length : actual.length === expected.length) && expected.every((part, index) => part === "$*" || part === actual[index]);
@@ -1392,7 +1428,16 @@ function captureAuthorizationFieldCatalog(schema, virtuals, documentPermissionFi
1392
1428
 
1393
1429
  // src/acl/populate-target-configuration.ts
1394
1430
  import { isPlainObject as isPlainObject11 } from "@web-ts-toolkit/utils";
1395
- function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions) {
1431
+
1432
+ // src/runtime-context.ts
1433
+ import { AsyncLocalStorage } from "async_hooks";
1434
+ var runtimeStorage = new AsyncLocalStorage();
1435
+ function getActiveRuntime() {
1436
+ return runtimeStorage.getStore() ?? null;
1437
+ }
1438
+
1439
+ // src/acl/populate-target-configuration.ts
1440
+ function capturePopulateTargetConfiguration(runtime, modelName, source, proposedOptions, defaults2 = runtime.getDefaultModelOptions()) {
1396
1441
  const label = `Populate target "${modelName}" for ${source}`;
1397
1442
  if (!proposedOptions && !runtime.hasModel(modelName))
1398
1443
  authorizationError(
@@ -1401,7 +1446,7 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
1401
1446
  const model = runtime.getModelInstance(modelName);
1402
1447
  if (!model) authorizationError(`${label} requires an actual registered Mongoose model in this runtime`);
1403
1448
  const options = proposedOptions ?? runtime.getModelOptions(modelName);
1404
- const permissionSchema = options.permissionSchema === void 0 ? runtime.getDefaultModelOption("permissionSchema") : options.permissionSchema;
1449
+ const permissionSchema = options.permissionSchema === void 0 ? defaults2.permissionSchema : options.permissionSchema;
1405
1450
  if (!isPlainObject11(permissionSchema))
1406
1451
  authorizationError(
1407
1452
  `${label} requires an effective object permissionSchema; configure the model or runtime model defaults ({} explicitly closes business fields)`
@@ -1409,6 +1454,31 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
1409
1454
  return { model, options: { ...options, permissionSchema } };
1410
1455
  }
1411
1456
 
1457
+ // src/acl/populate-policy.ts
1458
+ var defaults = /* @__PURE__ */ new WeakMap();
1459
+ function capturePopulatePolicyDefaults(runtime) {
1460
+ const options = runtime.getDefaultModelOptions();
1461
+ const token = () => {
1462
+ };
1463
+ defaults.set(
1464
+ token,
1465
+ Object.freeze({
1466
+ requireOperationAccessForPopulateQueries: options.requireOperationAccessForPopulateQueries !== false,
1467
+ requireOperationAccessForPopulateDependencies: options.requireOperationAccessForPopulateDependencies !== false
1468
+ })
1469
+ );
1470
+ return token;
1471
+ }
1472
+ function resolvePopulatePolicy(options, token) {
1473
+ const captured = defaults.get(token);
1474
+ if (!captured) return authorizationError("invalid captured populate model defaults");
1475
+ const resolve = (key) => (options[key] === void 0 ? captured[key] : options[key]) !== false;
1476
+ return Object.freeze({
1477
+ requireOperationAccessForPopulateQueries: resolve(populatePolicyKeys[0]),
1478
+ requireOperationAccessForPopulateDependencies: resolve(populatePolicyKeys[1])
1479
+ });
1480
+ }
1481
+
1412
1482
  // src/acl/virtual-populate-dependencies.ts
1413
1483
  var elementType = (type) => type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
1414
1484
  var join = (prefix, path) => prefix ? `${prefix}.${path}` : path;
@@ -1508,9 +1578,7 @@ function normalizeSelection(select, catalog, label) {
1508
1578
  includeId: selection.includes("_id")
1509
1579
  };
1510
1580
  }
1511
- function captureVirtualPopulateDependencies(runtime, modelName, options, globalOptions = runtime.getGlobalOptions()) {
1512
- const requireOperationAccessForPopulateDependencies = globalOptions.requireOperationAccessForPopulateDependencies !== false;
1513
- const requireOperationAccessForPopulateQueries = globalOptions.requireOperationAccessForPopulateQueries !== false;
1581
+ function captureVirtualPopulateDependencies(runtime, modelName, options, populatePolicyDefaults = capturePopulatePolicyDefaults(runtime), proposed) {
1514
1582
  const model = runtime.getModelInstance(modelName);
1515
1583
  const targets = /* @__PURE__ */ new Map();
1516
1584
  const scopes = [];
@@ -1554,18 +1622,19 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, globalO
1554
1622
  runtime,
1555
1623
  ref,
1556
1624
  `dependsOnPopulate virtual "${label}"`,
1557
- ref === modelName ? options : void 0
1625
+ ref === modelName ? options : proposed?.models.get(ref),
1626
+ proposed?.defaults
1558
1627
  );
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;
1628
+ const defaults2 = proposed?.defaults ?? runtime.getDefaultModelOptions();
1629
+ const readOption = (key) => resolveNestedOption((path2, fallback) => get2(targetOptions, path2, fallback), key, get2(defaults2, key));
1630
+ const documentPermissionField = targetOptions.documentPermissionField ?? defaults2.documentPermissionField;
1562
1631
  const catalog = captureAuthorizationFieldCatalog(targetModel.schema, void 0, documentPermissionField);
1563
1632
  const configuration = copyAuthorizationValue(
1564
1633
  {
1565
1634
  catalog,
1566
1635
  documentPermissionField,
1567
- requireOperationAccessForPopulateDependencies,
1568
- requireOperationAccessForPopulateQueries,
1636
+ populatePolicyDefaults,
1637
+ ...resolvePopulatePolicy(targetOptions, populatePolicyDefaults),
1569
1638
  permissionSchema: targetOptions.permissionSchema,
1570
1639
  operationAccess: { read: readOption("operationAccess.read") },
1571
1640
  baseFilter: { read: readOption("baseFilter.read") },
@@ -1660,6 +1729,15 @@ var defaultModelOptions = {
1660
1729
  basePath: null,
1661
1730
  alwaysSelectFields: []
1662
1731
  };
1732
+ var modelOverrides = (options) => {
1733
+ const result = Object.fromEntries(
1734
+ Object.entries(options).filter(
1735
+ ([key, value]) => value !== void 0 || key === "operationAccess" || isPopulatePolicyKey(key)
1736
+ )
1737
+ );
1738
+ for (const key of unsafeSnapshotOptions) if (key in result) result[key] = result[key] === true;
1739
+ return cloneOptionsSnapshot(result);
1740
+ };
1663
1741
  var defaultDataOptions = {
1664
1742
  basePath: null,
1665
1743
  parentPath: "/",
@@ -1793,12 +1871,12 @@ var getNestedChildFields = (parentSchema, fieldName) => {
1793
1871
  }
1794
1872
  return fields;
1795
1873
  };
1796
- var cloneVirtualsForValidation = (value) => {
1797
- if (Array.isArray(value)) return value.map((item) => cloneVirtualsForValidation(item));
1874
+ var cloneModelOptionForUpdate = (value) => {
1875
+ if (Array.isArray(value)) return value.map((item) => cloneModelOptionForUpdate(item));
1798
1876
  if (!value || typeof value !== "object") return value;
1799
1877
  if (Object.getPrototypeOf(value) !== Object.prototype) return value;
1800
1878
  return Object.fromEntries(
1801
- Object.entries(value).map(([k, v]) => [k, cloneVirtualsForValidation(v)])
1879
+ Object.entries(value).map(([k, v]) => [k, cloneModelOptionForUpdate(v)])
1802
1880
  );
1803
1881
  };
1804
1882
  var validateVirtualDependsOn = (dependsOn, entryLabel, storedFields, siblingVirtualNames) => {
@@ -1994,8 +2072,6 @@ var AccessRuntime = class {
1994
2072
  {
1995
2073
  requestPermissionField: "_permissions",
1996
2074
  globalPermissions: () => ({}),
1997
- requireOperationAccessForPopulateQueries: true,
1998
- requireOperationAccessForPopulateDependencies: true,
1999
2075
  logger: defaultLogger,
2000
2076
  requestComplexity: defaultRequestComplexity
2001
2077
  },
@@ -2010,15 +2086,20 @@ var AccessRuntime = class {
2010
2086
  queryRouteSegment: "__query",
2011
2087
  mutationRouteSegment: "__mutation",
2012
2088
  operationAccess: false,
2089
+ requireOperationAccessForPopulateQueries: true,
2090
+ requireOperationAccessForPopulateDependencies: true,
2013
2091
  modelPermissionPrefix: "",
2014
2092
  unsafeSkipListDocumentSnapshotChecks: false,
2015
2093
  unsafeSkipReadDocumentSnapshotChecks: false,
2016
2094
  unsafeSkipListOutputSnapshotChecks: false,
2017
2095
  unsafeSkipReadOutputSnapshotChecks: false,
2018
2096
  unsafeSkipListNestedDocumentSnapshotChecks: false,
2019
- unsafeSkipReadNestedDocumentSnapshotChecks: false
2097
+ unsafeSkipReadNestedDocumentSnapshotChecks: false,
2098
+ unsafeSkipListInitialOutputSnapshotCopy: false,
2099
+ unsafeSkipReadInitialOutputSnapshotCopy: false
2020
2100
  }).build();
2021
2101
  this.modelOptions = {};
2102
+ this.modelOptionOverrides = {};
2022
2103
  this.modelJsonSchemas = {};
2023
2104
  this.dataOptions = {};
2024
2105
  this.modelRefs = {};
@@ -2106,6 +2187,7 @@ var AccessRuntime = class {
2106
2187
  globalOptions: this.globalOptions.snapshot(),
2107
2188
  defaultModelOptions: this.defaultModelOptions.snapshot(),
2108
2189
  modelOptions: modelOptionsSnap,
2190
+ modelOptionOverrides: { ...this.modelOptionOverrides },
2109
2191
  dataOptions: dataOptionsSnap,
2110
2192
  modelInstances: { ...this.modelInstances },
2111
2193
  modelJsonSchemas: { ...this.modelJsonSchemas },
@@ -2120,6 +2202,10 @@ var AccessRuntime = class {
2120
2202
  restoreBootstrapSnapshot(snapshot) {
2121
2203
  this.globalOptions.restore(snapshot.globalOptions);
2122
2204
  this.defaultModelOptions.restore(snapshot.defaultModelOptions);
2205
+ for (const name of Object.keys(this.modelOptionOverrides)) delete this.modelOptionOverrides[name];
2206
+ for (const [name, options] of Object.entries(snapshot.modelOptionOverrides)) {
2207
+ this.modelOptionOverrides[name] = modelOverrides(options);
2208
+ }
2123
2209
  for (const name of Object.keys(this.modelOptions)) {
2124
2210
  if (!(name in snapshot.modelOptions)) {
2125
2211
  delete this.modelOptions[name];
@@ -2130,8 +2216,7 @@ var AccessRuntime = class {
2130
2216
  if (existing) {
2131
2217
  existing.restore(opts);
2132
2218
  } else {
2133
- const mgr = this.createModelOptions(name);
2134
- mgr.restore(opts);
2219
+ const mgr = this.createModelOptions(name, opts);
2135
2220
  this.modelOptions[name] = mgr;
2136
2221
  }
2137
2222
  }
@@ -2174,18 +2259,11 @@ var AccessRuntime = class {
2174
2259
  }
2175
2260
  /** Shallowly replace supplied global values; nested objects such as requestComplexity are not deep-merged. */
2176
2261
  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);
2262
+ for (const key of populatePolicyKeys) if (key in options) assertNoGlobalPopulatePolicy(key);
2263
+ this.globalOptions.assign({ ...options });
2183
2264
  }
2184
2265
  setGlobalOption(key, value) {
2185
- if (key === "requireOperationAccessForPopulateQueries" || key === "requireOperationAccessForPopulateDependencies") {
2186
- this.globalOptions.set(key, value !== false);
2187
- return;
2188
- }
2266
+ assertNoGlobalPopulatePolicy(String(key));
2189
2267
  this.globalOptions.set(key, value);
2190
2268
  }
2191
2269
  getGlobalOptions() {
@@ -2194,28 +2272,30 @@ var AccessRuntime = class {
2194
2272
  getGlobalOption(key, defaultValue) {
2195
2273
  return this.globalOptions.get(key, defaultValue);
2196
2274
  }
2197
- /** Update model starting defaults shallowly; already-stored model values are not broadcast-replaced. */
2275
+ /** Update inherited model defaults shallowly. Explicit model values and captured calls are unchanged. */
2198
2276
  setDefaultModelOptions(options) {
2199
2277
  assertPublicDefaults(options.defaults);
2200
2278
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
2201
- this.defaultModelOptions.assign(options);
2279
+ const draft = new OptionsManager(
2280
+ this.getDefaultModelOptions()
2281
+ ).build();
2282
+ draft.assign(normalizePopulatePolicyOptions(options));
2283
+ this.publishDefaultModelOptions(draft.fetch());
2202
2284
  }
2203
2285
  setDefaultModelOption(key, value) {
2204
2286
  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);
2287
+ const draft = new OptionsManager(
2288
+ this.getDefaultModelOptions()
2289
+ ).build();
2290
+ if (isPopulatePolicyKey(keyStr)) {
2291
+ draft.set(keyStr, normalizePopulatePolicyValue(value));
2292
+ } else if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
2293
+ draft.set("hydration", normalizeHydrationUpdate(this.getDefaultModelOptions().hydration, keyStr, value));
2294
+ } else {
2295
+ draft.set(key, value);
2217
2296
  }
2218
- this.defaultModelOptions.set(key, value);
2297
+ assertPublicDefaults(draft.fetch().defaults);
2298
+ this.publishDefaultModelOptions(draft.fetch());
2219
2299
  }
2220
2300
  getDefaultModelOptions() {
2221
2301
  return this.defaultModelOptions.fetch();
@@ -2223,30 +2303,103 @@ var AccessRuntime = class {
2223
2303
  getDefaultModelOption(key, defaultValue) {
2224
2304
  return this.defaultModelOptions.get(key, defaultValue);
2225
2305
  }
2226
- createModelOptions(modelName) {
2306
+ resolveModelOptions(modelName, overrides = this.modelOptionOverrides[modelName] ?? {}, defaults2 = this.getDefaultModelOptions()) {
2307
+ const inherited = { ...defaults2 };
2308
+ for (const key of populatePolicyKeys) delete inherited[key];
2309
+ const effective = { ...defaultModelOptions, ...inherited, ...overrides, modelName };
2310
+ effective.basePath = normalizeBasePath(modelName, effective.basePath);
2311
+ for (const key of unsafeSnapshotOptions) effective[key] = effective[key] === true;
2312
+ refreshPermissionMetadata(effective);
2313
+ return cloneOptionsSnapshot(effective);
2314
+ }
2315
+ validateModelOptions(modelName, options, proposed) {
2316
+ validateVirtualsTree(
2317
+ this.getModelInstance(modelName),
2318
+ options.virtuals,
2319
+ options.documentPermissionField ?? "_permissions",
2320
+ modelName
2321
+ );
2322
+ captureVirtualPopulateDependencies(this, modelName, options, void 0, proposed);
2323
+ }
2324
+ publishDefaultModelOptions(options) {
2325
+ const next = { ...options };
2326
+ for (const key of unsafeSnapshotOptions) if (key in next) next[key] = next[key] === true;
2327
+ const defaults2 = cloneOptionsSnapshot(next);
2328
+ const models = new Map(
2329
+ Object.keys(this.modelOptions).map((name) => [name, this.resolveModelOptions(name, void 0, defaults2)])
2330
+ );
2331
+ for (const [name, options2] of models) this.validateModelOptions(name, options2, { defaults: defaults2, models });
2332
+ this.deferSnapshotWarnings(() => {
2333
+ this.defaultModelOptions.restore(defaults2);
2334
+ for (const [name, options2] of models) this.modelOptions[name].restore(options2);
2335
+ });
2336
+ }
2337
+ warnSnapshotFlag(modelName, key) {
2338
+ if (this.pendingSnapshotWarnings) {
2339
+ this.pendingSnapshotWarnings.push({ modelName, key });
2340
+ return;
2341
+ }
2342
+ const operation = key.startsWith("unsafeSkipRead") ? "read" : "list";
2343
+ const category = key.includes("NestedDocument") ? "nested-document" : key.includes("Output") ? "output" : "document";
2344
+ const risk = category === "output" ? "output mutation" : "source mutation";
2345
+ try {
2346
+ this.getGlobalOption("logger")?.warn?.(
2347
+ `UNSAFE: ${operation} ${category} snapshot checks disabled; ${risk} can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
2348
+ { modelName }
2349
+ );
2350
+ } catch {
2351
+ }
2352
+ }
2353
+ deferSnapshotWarnings(publish) {
2354
+ if (this.pendingSnapshotWarnings) return publish();
2355
+ const copyModes = this.initialOutputCopyModes();
2356
+ const pending = [];
2357
+ this.pendingSnapshotWarnings = pending;
2358
+ let result;
2359
+ try {
2360
+ result = publish();
2361
+ } finally {
2362
+ this.pendingSnapshotWarnings = void 0;
2363
+ }
2364
+ const nextCopyModes = this.initialOutputCopyModes();
2365
+ for (const { modelName, key } of pending) this.warnSnapshotFlag(modelName, key);
2366
+ for (const [modelName, modes] of nextCopyModes) {
2367
+ for (const operation of ["List", "Read"]) {
2368
+ const mode = modes[operation];
2369
+ if (mode === "off" || mode === copyModes.get(modelName)?.[operation]) continue;
2370
+ const key = `unsafeSkip${operation}InitialOutputSnapshotCopy`;
2371
+ const prerequisite = `unsafeSkip${operation}OutputSnapshotChecks`;
2372
+ try {
2373
+ this.getGlobalOption("logger")?.warn?.(
2374
+ 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.`,
2375
+ { modelName }
2376
+ );
2377
+ } catch {
2378
+ }
2379
+ }
2380
+ }
2381
+ return result;
2382
+ }
2383
+ initialOutputCopyModes() {
2384
+ return new Map(
2385
+ Object.entries(this.modelOptions).map(([modelName, options]) => {
2386
+ const mode = (operation) => options.get(`unsafeSkip${operation}InitialOutputSnapshotCopy`) !== true ? "off" : options.get(`unsafeSkip${operation}OutputSnapshotChecks`) === true ? "active" : "dormant";
2387
+ return [modelName, { List: mode("List"), Read: mode("Read") }];
2388
+ })
2389
+ );
2390
+ }
2391
+ createModelOptions(modelName, options = this.resolveModelOptions(modelName)) {
2227
2392
  const model = this.getModelInstance(modelName);
2228
2393
  if (!model) {
2229
2394
  throw new Error(
2230
2395
  `Runtime model registry missing model "${modelName}". Pass a mongoose.Model instance to createRouter() or register it with registerModelInstance() before using this isolated runtime.`
2231
2396
  );
2232
2397
  }
2233
- const manager = new OptionsManager({
2234
- ...defaultModelOptions,
2235
- modelName
2236
- });
2398
+ const manager = new OptionsManager(options);
2237
2399
  const snapshotFlagChanged = (newValue, key, target, oldValue) => {
2238
2400
  target[key] = newValue === true;
2239
2401
  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
- }
2402
+ this.warnSnapshotFlag(modelName, key);
2250
2403
  };
2251
2404
  manager.onchange("permissionSchema", function(_newval, _key, target) {
2252
2405
  refreshPermissionMetadata(target);
@@ -2264,13 +2417,17 @@ var AccessRuntime = class {
2264
2417
  getOrCreateModelOptions(modelName) {
2265
2418
  let manager = this.modelOptions[modelName];
2266
2419
  if (!manager) {
2267
- manager = this.createModelOptions(modelName);
2268
- this.modelOptions[modelName] = manager;
2420
+ manager = this.deferSnapshotWarnings(() => {
2421
+ const created = this.createModelOptions(modelName);
2422
+ this.modelOptions[modelName] = created;
2423
+ return created;
2424
+ });
2269
2425
  }
2270
2426
  return manager;
2271
2427
  }
2272
2428
  /**
2273
- * Assign `{ ...modelDefaults, ...storedOptions, ...options }` shallowly. A supplied
2429
+ * Update explicit model overrides shallowly; undefined restores default inheritance
2430
+ * (operationAccess preserves its existing exact-key-only default fallback). A supplied
2274
2431
  * operationAccess/defaults object replaces that whole value. Defaults accept only
2275
2432
  * query/presentation settings; virtual configuration is validated before assignment.
2276
2433
  * Existing router.options remains its construction-time snapshot. Fresh model-service
@@ -2278,22 +2435,23 @@ var AccessRuntime = class {
2278
2435
  */
2279
2436
  setModelOptions(modelName, options) {
2280
2437
  assertPublicDefaults(options.defaults);
2438
+ options = normalizePopulatePolicyOptions(options);
2281
2439
  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 });
2440
+ const overrides = modelOverrides({ ...this.modelOptionOverrides[modelName], ...options });
2441
+ const effective = this.resolveModelOptions(modelName, overrides);
2442
+ this.validateModelOptions(modelName, effective);
2443
+ this.deferSnapshotWarnings(() => {
2444
+ const manager = this.modelOptions[modelName];
2445
+ if (manager) manager.restore(effective);
2446
+ else this.modelOptions[modelName] = this.createModelOptions(modelName, effective);
2447
+ this.modelOptionOverrides[modelName] = overrides;
2448
+ });
2291
2449
  }
2292
2450
  setModelOption(modelName, key, value) {
2293
2451
  const keyStr = String(key);
2294
2452
  if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
2295
- const hydration = normalizeHydrationUpdate(this.modelOptions[modelName]?.get("hydration"), keyStr, value);
2296
- this.getOrCreateModelOptions(modelName).set("hydration", hydration);
2453
+ const hydration = normalizeHydrationUpdate(this.resolveModelOptions(modelName).hydration, keyStr, value);
2454
+ this.setModelOptions(modelName, { hydration });
2297
2455
  return;
2298
2456
  }
2299
2457
  if (keyStr === "defaults") assertPublicDefaults(value);
@@ -2302,47 +2460,20 @@ var AccessRuntime = class {
2302
2460
  set3(proposed, keyStr.slice("defaults.".length), value);
2303
2461
  assertPublicDefaults(proposed);
2304
2462
  }
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
- });
2463
+ const [root, ...path] = keyStr.split(".");
2464
+ if (!path.length) {
2465
+ this.setModelOptions(modelName, { [root]: value });
2466
+ return;
2342
2467
  }
2343
- this.getOrCreateModelOptions(modelName).set(key, value);
2468
+ const current = this.resolveModelOptions(modelName);
2469
+ const nested = cloneModelOptionForUpdate(isPlainObject13(current[root]) ? current[root] : {});
2470
+ if (root === "virtuals" && value === void 0) {
2471
+ const parent = path.length === 1 ? nested : get3(nested, path.slice(0, -1));
2472
+ if (isPlainObject13(parent)) delete parent[path[path.length - 1]];
2473
+ } else set3(nested, path, value);
2474
+ this.setModelOptions(modelName, { [root]: nested });
2344
2475
  }
2345
- /** Frozen stored snapshot, not fully resolved per-path defaults. Read again for current configuration. */
2476
+ /** Frozen model/default snapshot; populate flags remain raw overrides. Read again for current values. */
2346
2477
  getModelOptions(modelName) {
2347
2478
  const manager = this.getOrCreateModelOptions(modelName);
2348
2479
  return manager.fetch();
@@ -2507,13 +2638,6 @@ var AccessRuntime = class {
2507
2638
  };
2508
2639
  var defaultRuntime = new AccessRuntime({ allowGlobalModelLookup: true });
2509
2640
 
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
2641
  // src/options/global-options.ts
2518
2642
  var getRuntime = () => getActiveRuntime() ?? defaultRuntime;
2519
2643
  var getGlobalOption = (key, defaultValue) => {