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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/advanced.js CHANGED
@@ -126,235 +126,1224 @@ var FilterOperator = /* @__PURE__ */ ((FilterOperator2) => {
126
126
  var import_express_json_router3 = __toESM(require("@web-ts-toolkit/express-json-router"));
127
127
 
128
128
  // src/runtime.ts
129
- var import_mongoose3 = __toESM(require("mongoose"));
129
+ var import_mongoose4 = __toESM(require("mongoose"));
130
130
 
131
131
  // src/validation/public-admission.ts
132
+ var import_express_json_router2 = __toESM(require("@web-ts-toolkit/express-json-router"));
133
+ var import_node_util6 = require("util");
134
+ var import_utils2 = require("@web-ts-toolkit/utils");
135
+
136
+ // src/acl/output-work-ledger.ts
137
+ var import_node_async_hooks = require("async_hooks");
138
+
139
+ // src/acl/authorization-snapshot.ts
140
+ var import_node_util4 = require("util");
141
+ var import_mongoose2 = require("mongoose");
132
142
  var import_express_json_router = __toESM(require("@web-ts-toolkit/express-json-router"));
133
- var import_utils = require("@web-ts-toolkit/utils");
134
143
 
135
- // src/acl/unsafe-snapshot-options.ts
136
- var unsafeSnapshotCheckOptions = [
137
- "unsafeSkipListDocumentSnapshotChecks",
138
- "unsafeSkipReadDocumentSnapshotChecks",
139
- "unsafeSkipListOutputSnapshotChecks",
140
- "unsafeSkipReadOutputSnapshotChecks",
141
- "unsafeSkipListNestedDocumentSnapshotChecks",
142
- "unsafeSkipReadNestedDocumentSnapshotChecks"
143
- ];
144
- var unsafeInitialOutputCopyOptions = [
145
- "unsafeSkipListInitialOutputSnapshotCopy",
146
- "unsafeSkipReadInitialOutputSnapshotCopy"
147
- ];
148
- var unsafeSnapshotOptions = [...unsafeSnapshotCheckOptions, ...unsafeInitialOutputCopyOptions];
149
- var unsafeAuthorizationFastPathOptions = [
150
- "unsafeUseListAuthorizationFastPath",
151
- "unsafeUseReadAuthorizationFastPath"
152
- ];
153
- var unsafeServerOptions = [...unsafeSnapshotOptions, ...unsafeAuthorizationFastPathOptions];
154
- function authorizationFastPathPrerequisites(origin) {
155
- const operation = origin === "read" ? "Read" : "List";
156
- return [
157
- `unsafeSkip${operation}DocumentSnapshotChecks`,
158
- `unsafeSkip${operation}OutputSnapshotChecks`,
159
- `unsafeSkip${operation}NestedDocumentSnapshotChecks`,
160
- `unsafeSkip${operation}InitialOutputSnapshotCopy`
161
- ];
162
- }
163
- function captureAuthorizationFastPath(options, origin) {
164
- const literalTrue = (key2) => {
165
- const descriptor = Object.getOwnPropertyDescriptor(options, key2);
166
- return !!descriptor && "value" in descriptor && descriptor.value === true;
167
- };
168
- const key = origin === "read" ? unsafeAuthorizationFastPathOptions[1] : unsafeAuthorizationFastPathOptions[0];
169
- const requested = literalTrue(key);
170
- const prerequisites = authorizationFastPathPrerequisites(origin).reduce(
171
- (mask, key2, index) => mask | (literalTrue(key2) ? 1 << index : 0),
172
- 0
173
- );
174
- return Object.freeze({
175
- origin,
176
- mode: !requested ? "off" : prerequisites === 15 ? "active" : "dormant",
177
- prerequisites
178
- });
144
+ // src/acl/field-catalog.ts
145
+ var import_node_util = require("util");
146
+ var ownedCatalogs = /* @__PURE__ */ new WeakMap();
147
+ function readOwnedAuthorizationCatalogWork(value) {
148
+ return ownedCatalogs.get(value);
179
149
  }
180
-
181
- // src/validation/public-admission.ts
182
- var privateControls = [
183
- "authorization",
184
- "overrides",
150
+ var safeSegment = (part) => !!part && part !== "sub" && !["__proto__", "constructor", "prototype", "_doc", "__v"].includes(part) && !/^[+$-]|[\s*]/.test(part) && !part.includes("[") && !part.includes("]") && !/^\d+$/.test(part) && !hasControlCharacter(part);
151
+ function hasControlCharacter(part) {
152
+ for (let index = 0; index < part.length; index++) {
153
+ const code = part.charCodeAt(index);
154
+ if (code < 32 || code === 127) return true;
155
+ }
156
+ return false;
157
+ }
158
+ function prepareCatalogPathParts(path) {
159
+ const ledger = currentOutputWorkLedger();
160
+ if (ledger) {
161
+ let segments = 1;
162
+ for (let index = 0; index < path.length; index++) if (path.charCodeAt(index) === 46) segments++;
163
+ debitOutputWork(ledger, segments);
164
+ debitOutputPayload(ledger, path);
165
+ }
166
+ }
167
+ function catalogPathParts(path) {
168
+ prepareCatalogPathParts(path);
169
+ return path.split(".");
170
+ }
171
+ var isSafeOutputPath = (path) => catalogPathParts(path).every(safeSegment);
172
+ var inputControlSegments = /* @__PURE__ */ new Set([
173
+ "_permissions",
174
+ "_view",
175
+ "_edit",
185
176
  "documentAuthorization",
186
177
  "documentAuthorizationStage",
178
+ "resolvedAuthorization",
187
179
  "execution",
188
180
  "executionContext",
189
181
  "serviceExecutionContext",
190
- "snapshotDerivation",
191
- "resolvedAuthorization",
192
182
  "preparedQuery",
193
183
  "preparedFilter",
194
184
  "preparedModelQuery",
195
185
  "resolvedIdentifier",
196
186
  "skipParsing",
197
187
  "skipAuthorization",
198
- "alreadyAuthorized",
199
- ...unsafeServerOptions,
200
- "operation"
201
- ];
202
- var PublicAdmissionError = class extends import_express_json_router.default.clientErrors.BadRequestError {
203
- constructor(detail) {
204
- const errors = [{ detail }];
205
- super("Bad Request", { errors });
206
- this.result = { success: false, kind: "error", code: "bad_request" /* BadRequest */, errors };
188
+ "alreadyAuthorized"
189
+ ]);
190
+ function isSafeInputPath(path, requestIdentity = false) {
191
+ return isSafeOutputPath(path) && path.split(".").every((part) => !inputControlSegments.has(part) && (requestIdentity || part !== "_id"));
192
+ }
193
+ function matchesCatalogPattern(pattern, path, descendants = false) {
194
+ debitOutputWork();
195
+ if (typeof pattern === "string" && typeof path === "string" && !pattern.includes("$*")) {
196
+ return pattern === path || !!descendants && path.startsWith(pattern) && path[pattern.length] === ".";
207
197
  }
208
- };
209
- var defaultControlBuckets = [
210
- "findOneArgs",
211
- "findOneOptions",
212
- "findByIdArgs",
213
- "findByIdOptions",
214
- "findArgs",
215
- "findOptions",
216
- "createArgs",
217
- "createOptions",
218
- "updateOneArgs",
219
- "updateOneOptions",
220
- "upsertOptions",
221
- "updateByIdArgs",
222
- "upsertArgs",
223
- "updateByIdOptions",
224
- "existsOptions",
225
- "publicListArgs",
226
- "publicListOptions",
227
- "publicCreateArgs",
228
- "publicCreateOptions",
229
- "publicReadArgs",
230
- "publicReadOptions",
231
- "publicUpdateArgs",
232
- "publicUpdateOptions"
233
- ];
234
- function assertPublicAdmission(input, kind = "envelope") {
235
- assertPublicControlAdmission(input, kind);
198
+ prepareCatalogPathParts(pattern);
199
+ const expected = pattern.split(".");
200
+ prepareCatalogPathParts(path);
201
+ const actual = path.split(".");
202
+ return (descendants ? actual.length >= expected.length : actual.length === expected.length) && expected.every((part, index) => part === "$*" || part === actual[index]);
236
203
  }
237
- function assertPublicControlAdmission(input, kind) {
238
- walkControlAdmission(
239
- input,
240
- kind,
241
- (record2, path) => {
242
- for (const key of privateControls) {
243
- if (key in record2) {
244
- throw new PublicAdmissionError(
245
- unsafeServerOptions.includes(key) ? `Unsupported public control ${path}.${key}; this unsafe flag is server model configuration only` : `Unsupported public control ${path}.${key}; use explicit per-call internal service options for backend authorization`
246
- );
247
- }
248
- }
249
- },
250
- (detail) => {
251
- throw new PublicAdmissionError(detail);
204
+ function captureAuthorizationFieldCatalog(schema, virtuals, documentPermissionField = "_permissions") {
205
+ debitOutputPayload(currentOutputWorkLedger(), documentPermissionField);
206
+ const paths = /* @__PURE__ */ new Set();
207
+ const containers = /* @__PURE__ */ new Set();
208
+ const opaque = /* @__PURE__ */ new Set();
209
+ const references = /* @__PURE__ */ new Set();
210
+ const virtualPaths = /* @__PURE__ */ new Set();
211
+ const virtualScopes = /* @__PURE__ */ new Set();
212
+ const schemaVirtualPaths = /* @__PURE__ */ new Set();
213
+ const arrays = /* @__PURE__ */ new Set();
214
+ const protectedPaths = /* @__PURE__ */ new Set([documentPermissionField, "_doc", "$__", "__v"]);
215
+ const add = (path) => {
216
+ debitOutputWork();
217
+ debitOutputPayload(currentOutputWorkLedger(), path);
218
+ if (catalogPathParts(path).every((part) => part === "$*" || safeSegment(part))) paths.add(path);
219
+ };
220
+ const ancestors = (path) => {
221
+ const parts = catalogPathParts(path);
222
+ for (let n = 1; n < parts.length; n++) {
223
+ debitOutputWork(void 0, n);
224
+ const parent = prepareOutputWorkString(parts.slice(0, n));
225
+ add(parent);
226
+ containers.add(parent);
252
227
  }
253
- );
254
- }
255
- function walkControlAdmission(input, kind, check, reject) {
256
- const pending = [{ value: input, kind, path: "request", depth: 0 }];
257
- const seen = /* @__PURE__ */ new WeakMap();
258
- let slots = 1;
259
- while (pending.length) {
260
- const { value, kind: slot, path, depth } = pending.pop();
261
- if (!value || typeof value !== "object" && typeof value !== "function") continue;
262
- const kinds = seen.get(value) ?? /* @__PURE__ */ new Set();
263
- if (kinds.has(slot)) continue;
264
- kinds.add(slot);
265
- seen.set(value, kinds);
266
- const add = (child, childKind, key) => {
267
- if (child === void 0 || child === null) return;
268
- if (++slots > 2e4 || depth >= 100) reject("control admission exceeds structural limits");
269
- pending.push({ value: child, kind: childKind, path: `${path}.${key}`, depth: depth + 1 });
270
- };
271
- const record2 = value;
272
- if (slot !== "data" && slot !== "policies") check(record2, path);
273
- const read = (key) => {
274
- let owner = value;
275
- for (let depth2 = 0; owner; depth2++, owner = Object.getPrototypeOf(owner)) {
276
- if (depth2 > 100) reject("control admission prototype depth exceeded");
277
- const descriptor = Object.getOwnPropertyDescriptor(owner, key);
278
- if (!descriptor) continue;
279
- if (!("value" in descriptor)) reject(`accessor control/data property: ${path}.${key}`);
280
- return descriptor.value;
281
- }
282
- return void 0;
283
- };
284
- if (Array.isArray(value)) {
285
- if (value.length > 2e4) reject("control admission array exceeds structural limits");
286
- for (let index = 0; index < value.length; index++) {
287
- if (index in value) add(read(String(index)), slot, String(index));
288
- }
289
- continue;
228
+ };
229
+ const visitType = (type, path, active) => {
230
+ debitOutputWork();
231
+ add(path);
232
+ ancestors(path);
233
+ const element = type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
234
+ if (type.instance === "Array" || type.$isMongooseDocumentArray) arrays.add(path);
235
+ if (type.options?.ref || type.options?.refPath || element?.options?.ref || element?.options?.refPath) {
236
+ references.add(path);
237
+ return;
290
238
  }
291
- if (slot === "data") {
292
- if (!(0, import_utils.isPlainObject)(value)) continue;
293
- add(read("$$sq"), "envelope", "$$sq");
294
- for (const key of Object.keys(value)) if (key !== "$$sq") add(read(key), "data", key);
295
- continue;
239
+ if (type.$isSchemaMap || type.instance === "Map") {
240
+ const value = type.$__schemaType;
241
+ if (value) visitType(value, prepareOutputWorkString([path, "$*"]), active);
242
+ else opaque.add(path);
243
+ containers.delete(path);
244
+ return;
296
245
  }
297
- if (slot === "defaults") {
298
- const keys2 = /* @__PURE__ */ new Set([...Object.keys(value), ...defaultControlBuckets]);
299
- if (keys2.size > 2e4) reject("control admission defaults exceeds structural limits");
300
- for (const key of keys2) if (key in record2) add(read(key), "envelope", key);
301
- continue;
246
+ const child = type.schema ?? element?.schema;
247
+ if (child) {
248
+ containers.add(path);
249
+ if (!active.has(child)) visitSchema(child, path, /* @__PURE__ */ new Set([...active, child]));
250
+ return;
302
251
  }
303
- if (slot === "policies") {
304
- for (const key of Object.keys(value)) add(read(key), "policy", key);
305
- continue;
252
+ if (type.instance === "Mixed" || element?.instance === "Mixed") opaque.add(path);
253
+ };
254
+ const visitSchema = (current, prefix, active) => {
255
+ debitOutputWork();
256
+ const version = current.options.versionKey;
257
+ if (typeof version === "string") protectedPaths.add(prefix ? `${prefix}.${version}` : version);
258
+ for (const name of Object.keys(current.virtuals)) {
259
+ debitOutputWork();
260
+ schemaVirtualPaths.add(prefix ? prepareOutputWorkString([prefix, name]) : name);
306
261
  }
307
- if (slot === "policy") {
308
- for (const key of ["rows", "outputFields", "inputFields", "operation"]) add(read(key), "policy", key);
309
- add(read("related"), "policies", "related");
310
- add(read("filter"), "data", "filter");
311
- continue;
262
+ for (const [name, raw] of Object.entries(current.paths)) {
263
+ debitOutputWork();
264
+ if (name.includes("$*")) continue;
265
+ visitType(raw, prefix ? prepareOutputWorkString([prefix, name]) : name, active);
312
266
  }
313
- for (const key of ["args", "options", "sqOptions"]) add(read(key), "envelope", key);
314
- add(read("include"), "include", "include");
315
- add(read("populate"), "populate", "populate");
316
- add(read("authorization"), "policy", "authorization");
317
- for (const key of ["filter", "match", "data"]) add(read(key), "data", key);
318
- }
319
- }
320
- function assertHydrationDefaults(defaults2) {
321
- if (defaults2 && typeof defaults2 === "object") {
322
- const record2 = defaults2;
323
- if ("hydration" in record2)
324
- throw new TypeError("defaults.hydration is unsupported; use model hydration configuration");
325
- for (const bucket of [
326
- "publicListOptions",
327
- "publicReadOptions",
328
- "findOptions",
329
- "findOneOptions",
330
- "findByIdOptions",
331
- "createOptions",
332
- "updateOneOptions",
333
- "updateByIdOptions",
334
- "upsertOptions",
335
- "existsOptions",
336
- "publicCreateOptions",
337
- "publicUpdateOptions"
338
- ]) {
339
- const options = record2[bucket];
340
- if (!options || typeof options !== "object" && typeof options !== "function") continue;
341
- for (const key of ["lean", "hydration"]) {
342
- if (!(key in options)) continue;
343
- const method = bucket.slice(0, -"Options".length);
344
- const migration = ["publicList", "publicRead", "find", "findOne", "findById"].includes(method) ? `use model hydration.${method} ('lean' or 'hydrated')` : "this method has a fixed fetch mode";
345
- throw new TypeError(`defaults.${bucket}.${key} is unsupported; ${migration}`);
267
+ };
268
+ visitSchema(schema, "", /* @__PURE__ */ new Set([schema]));
269
+ const copyPaths = (values) => {
270
+ debitOutputWork(void 0, 1 + (Array.isArray(values) ? values.length : values.size));
271
+ return [...values];
272
+ };
273
+ const persistedPaths = copyPaths(paths);
274
+ const visitVirtuals = (record2, prefix) => {
275
+ for (const [name, value] of Object.entries(record2 ?? {})) {
276
+ debitOutputWork();
277
+ if (value === void 0) continue;
278
+ const path = prefix ? prepareOutputWorkString([prefix, name]) : name;
279
+ debitOutputPayload(currentOutputWorkLedger(), path);
280
+ if (!isSafeOutputPath(path)) continue;
281
+ if (value && typeof value === "object" && "sub" in value) {
282
+ if (references.has(path)) continue;
283
+ virtualScopes.add(path);
284
+ add(path);
285
+ containers.add(path);
286
+ visitVirtuals(value.sub, path);
287
+ } else {
288
+ add(path);
289
+ ancestors(path);
290
+ virtualPaths.add(path);
346
291
  }
347
292
  }
293
+ };
294
+ visitVirtuals(virtuals, "");
295
+ const protectedEntries = copyPaths(protectedPaths);
296
+ const filterPaths = (values, keep) => {
297
+ debitOutputWork(void 0, values.length + 1);
298
+ return values.filter(keep);
299
+ };
300
+ const eligible = filterPaths(
301
+ copyPaths(paths),
302
+ (p) => !protectedEntries.some((v) => matchesCatalogPattern(v, p, true))
303
+ );
304
+ debitOutputWork(void 0, 3);
305
+ const catalog = Object.freeze({
306
+ paths: Object.freeze(filterPaths(eligible, (p) => !p.includes("$*"))),
307
+ persistedPaths: Object.freeze(persistedPaths),
308
+ arrayPaths: Object.freeze(copyPaths(arrays)),
309
+ schemaVirtualPaths: Object.freeze(copyPaths(schemaVirtualPaths)),
310
+ metadataPaths: Object.freeze([documentPermissionField]),
311
+ dynamicPaths: Object.freeze(filterPaths(eligible, (p) => p.includes("$*"))),
312
+ containerPaths: Object.freeze(copyPaths(containers)),
313
+ opaquePaths: Object.freeze(copyPaths(opaque)),
314
+ referencePaths: Object.freeze(copyPaths(references)),
315
+ virtualPaths: Object.freeze(copyPaths(virtualPaths)),
316
+ virtualScopePaths: Object.freeze(copyPaths(virtualScopes)),
317
+ protectedPaths: Object.freeze(protectedEntries)
318
+ });
319
+ if (typeof documentPermissionField === "string") {
320
+ const arrays2 = Object.values(catalog);
321
+ ownedCatalogs.set(
322
+ catalog,
323
+ Object.freeze({ slots: 1 + arrays2.length + arrays2.reduce((sum, paths2) => sum + paths2.length, 0), depth: 2 })
324
+ );
348
325
  }
326
+ return catalog;
349
327
  }
350
- function assertPublicDefaults(defaults2) {
351
- assertPublicControlAdmission(defaults2, "defaults");
352
- assertHydrationDefaults(defaults2);
353
- }
354
- var requestAuthorization = Object.freeze({ outputFields: Object.freeze({ mode: "request" }) });
355
328
 
356
- // src/options/hydration.ts
357
- var methods = ["publicList", "publicRead", "find", "findOne", "findById"];
329
+ // src/acl/trusted-output-materialization.ts
330
+ var import_node_util3 = require("util");
331
+ var import_mongoose = require("mongoose");
332
+
333
+ // src/output/permissions-alias.ts
334
+ var import_utils = require("@web-ts-toolkit/utils");
335
+ var import_node_util2 = require("util");
336
+ var aliases = /* @__PURE__ */ new WeakMap();
337
+ function isGeneratedPermissionsAliasSlot(output, key, slot) {
338
+ return key === "permissions" && aliases.has(output) && "value" in slot && !slot.enumerable;
339
+ }
340
+ function attachPermissionsAlias(output, field) {
341
+ if ("permissions" in output) return;
342
+ const metadata = (0, import_utils.get)(output, field);
343
+ if (metadata === void 0) return;
344
+ Object.defineProperty(output, "permissions", {
345
+ value: metadata,
346
+ enumerable: false,
347
+ writable: true,
348
+ configurable: true
349
+ });
350
+ aliases.set(output, field);
351
+ }
352
+ function copyPermissionsAlias(source, target) {
353
+ if (source && typeof source === "object" && target && typeof target === "object") {
354
+ const field = aliases.get(source);
355
+ const readData = (value) => {
356
+ const parts = field?.split(".") ?? [];
357
+ if (parts.length > 100) return void 0;
358
+ for (const key of parts) {
359
+ if (!value || typeof value !== "object" || import_node_util2.types.isProxy(value)) return void 0;
360
+ const slot = Object.getOwnPropertyDescriptor(value, key);
361
+ if (!slot || !("value" in slot)) return void 0;
362
+ value = slot.value;
363
+ }
364
+ return value;
365
+ };
366
+ if (field && readData(target) !== void 0 && Object.getOwnPropertyDescriptor(source, "permissions")?.value === readData(source))
367
+ attachPermissionsAlias(target, field);
368
+ }
369
+ return target;
370
+ }
371
+
372
+ // src/acl/trusted-output-materialization.ts
373
+ var unsafeKeys = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype", "_doc", "$__"]);
374
+ var protectedValueKeys = /* @__PURE__ */ new Set([...unsafeKeys, "__v"]);
375
+ var budgets = /* @__PURE__ */ new WeakMap();
376
+ function createTrustedOutputBudget(onFailure, ownerCheck, ledger) {
377
+ const budget = Object.freeze(/* @__PURE__ */ Object.create(null));
378
+ const ownerLedger = arguments.length < 3 ? currentOutputWorkLedger() : ledger;
379
+ budgets.set(budget, {
380
+ slots: 0,
381
+ failure: void 0,
382
+ recipients: void 0,
383
+ onFailure,
384
+ ownerCheck,
385
+ ledger: ownerLedger
386
+ });
387
+ return budget;
388
+ }
389
+ function failTrustedOutputBudget(budget, error) {
390
+ const record2 = budgets.get(budget);
391
+ if (!record2) authorizationError("invalid selected output budget");
392
+ record2.failure ??= error instanceof ServiceAuthorizationError ? error : new ServiceAuthorizationError("unsupported selected value");
393
+ record2.onFailure?.(record2.failure);
394
+ for (const edge of record2.recipients ?? []) {
395
+ try {
396
+ failTrustedOutputBudget(edge.budget, record2.failure);
397
+ } catch {
398
+ }
399
+ }
400
+ throw record2.failure;
401
+ }
402
+ function assertTrustedOutputBudget(budget) {
403
+ const record2 = budgets.get(budget);
404
+ if (!record2) authorizationError("invalid selected output budget");
405
+ record2.ownerCheck?.();
406
+ record2.ledger?.check();
407
+ if (record2.failure) throw record2.failure;
408
+ for (const edge of record2.recipients ?? []) assertTrustedOutputBudget(edge.budget);
409
+ }
410
+ function visitTrustedOutput(budget, depth, slots = 1, charged) {
411
+ const record2 = budgets.get(budget);
412
+ if (!record2) authorizationError("invalid selected output budget");
413
+ assertTrustedOutputBudget(budget);
414
+ if (record2.recipients?.length) charged ??= /* @__PURE__ */ new Set();
415
+ if (record2.ledger && !charged?.has(record2.ledger)) {
416
+ debitOutputWork(record2.ledger, slots);
417
+ charged?.add(record2.ledger);
418
+ }
419
+ if (depth > 100 || (record2.slots += slots) > 2e4)
420
+ failTrustedOutputBudget(budget, new ServiceAuthorizationError("selected output exceeds structural limits"));
421
+ try {
422
+ for (const edge of record2.recipients ?? [])
423
+ visitTrustedOutput(edge.budget, depth + edge.depth, slots * edge.multiplicity, charged);
424
+ } catch (error) {
425
+ failTrustedOutputBudget(budget, error);
426
+ }
427
+ }
428
+ function preloadTrustedOutputBudget(budget, depth, slots) {
429
+ const record2 = budgets.get(budget);
430
+ if (!record2) authorizationError("invalid selected output budget");
431
+ visitTrustedOutput(budget, depth, slots, record2.ledger ? /* @__PURE__ */ new Set([record2.ledger]) : void 0);
432
+ }
433
+ function prepareTrustedOutputPayload(budget, value, charged) {
434
+ const record2 = budgets.get(budget);
435
+ if (!record2) authorizationError("invalid selected output budget");
436
+ if (!record2.ledger && !record2.recipients?.length) return;
437
+ assertTrustedOutputBudget(budget);
438
+ if (record2.recipients?.length) charged ??= /* @__PURE__ */ new Set();
439
+ if (record2.ledger && !charged?.has(record2.ledger)) {
440
+ debitOutputPayload(record2.ledger, value);
441
+ charged?.add(record2.ledger);
442
+ }
443
+ for (const edge of record2.recipients ?? []) prepareTrustedOutputPayload(edge.budget, value, charged);
444
+ }
445
+ function defineTrustedOutputValue(output, key, value) {
446
+ Object.defineProperty(output, key, { value, enumerable: true, configurable: true, writable: true });
447
+ }
448
+ function isBsonValue(input) {
449
+ let prototype = Object.getPrototypeOf(input);
450
+ for (let depth = 0; prototype && depth <= 100; depth++) {
451
+ debitOutputWork();
452
+ if (import_node_util3.types.isProxy(prototype)) return false;
453
+ if (prototype === import_mongoose.mongo.BSON.BSONValue.prototype) return true;
454
+ prototype = Object.getPrototypeOf(prototype);
455
+ }
456
+ return false;
457
+ }
458
+ var bsonFamilies = new Map(
459
+ Object.entries({
460
+ ObjectId: import_mongoose.mongo.BSON.ObjectId,
461
+ Code: import_mongoose.mongo.BSON.Code,
462
+ DBRef: import_mongoose.mongo.BSON.DBRef,
463
+ Timestamp: import_mongoose.mongo.BSON.Timestamp,
464
+ Long: import_mongoose.mongo.BSON.Long,
465
+ Decimal128: import_mongoose.mongo.BSON.Decimal128,
466
+ Binary: import_mongoose.mongo.BSON.Binary,
467
+ Double: import_mongoose.mongo.BSON.Double,
468
+ Int32: import_mongoose.mongo.BSON.Int32,
469
+ BSONRegExp: import_mongoose.mongo.BSON.BSONRegExp,
470
+ BSONSymbol: import_mongoose.mongo.BSON.BSONSymbol,
471
+ MinKey: import_mongoose.mongo.BSON.MinKey,
472
+ MaxKey: import_mongoose.mongo.BSON.MaxKey
473
+ }).map(([name, family]) => [family.prototype, name])
474
+ );
475
+ function selectedDataProperty(input, key, own = false) {
476
+ let object = input;
477
+ for (let depth = 0; object && depth <= 100; depth++) {
478
+ debitOutputWork();
479
+ if (import_node_util3.types.isProxy(object)) authorizationError("unsupported selected proxy");
480
+ const slot = Object.getOwnPropertyDescriptor(object, key);
481
+ if (slot) {
482
+ if (!("value" in slot)) authorizationError("accessor selected BSON state");
483
+ return slot.value;
484
+ }
485
+ object = own ? null : Object.getPrototypeOf(object);
486
+ }
487
+ if (object) authorizationError("unsupported selected prototype depth");
488
+ return void 0;
489
+ }
490
+ function selectedBsonBytes(input, budget) {
491
+ if (!input || typeof input !== "object" || import_node_util3.types.isProxy(input) || !import_node_util3.types.isUint8Array(input))
492
+ authorizationError("unsupported selected BSON bytes");
493
+ const prototype = Object.getPrototypeOf(Uint8Array.prototype);
494
+ const buffer = Object.getOwnPropertyDescriptor(prototype, "buffer").get.call(input);
495
+ const offset = Object.getOwnPropertyDescriptor(prototype, "byteOffset").get.call(input);
496
+ const length = Object.getOwnPropertyDescriptor(prototype, "byteLength").get.call(input);
497
+ prepareTrustedOutputPayload(budget, length);
498
+ return Buffer.from(new Uint8Array(buffer, offset, length));
499
+ }
500
+ var regexpFlagNames = [
501
+ "hasIndices",
502
+ "global",
503
+ "ignoreCase",
504
+ "multiline",
505
+ "dotAll",
506
+ "unicode",
507
+ "unicodeSets",
508
+ "sticky"
509
+ ];
510
+ function prepareRegExpFlags(input, budget) {
511
+ const ledger = budgets.get(budget).ledger;
512
+ if (ledger) debitOutputWork(ledger, regexpFlagNames.length);
513
+ const flags = [];
514
+ for (let index = 0; index < regexpFlagNames.length; index++)
515
+ if (Object.getOwnPropertyDescriptor(RegExp.prototype, regexpFlagNames[index])?.get?.call(input)) {
516
+ prepareTrustedOutputPayload(budget, 1);
517
+ defineTrustedOutputValue(flags, String(flags.length), "dgimsuvy"[index]);
518
+ }
519
+ prepareTrustedOutputPayload(budget, flags.length);
520
+ return flags.join("");
521
+ }
522
+ function copyTrustedBsonValue(value, path, budget, policy, depth, active) {
523
+ const wireKeys = /* @__PURE__ */ new Set([
524
+ "value",
525
+ "code",
526
+ "scope",
527
+ "collection",
528
+ "oid",
529
+ "db",
530
+ "fields",
531
+ "low",
532
+ "high",
533
+ "unsigned",
534
+ "buffer",
535
+ "sub_type",
536
+ "position",
537
+ "pattern",
538
+ "options",
539
+ "bytes",
540
+ "i0",
541
+ "i1",
542
+ "i2",
543
+ "i3"
544
+ ]);
545
+ const defineWireValue = (output, key, value2) => {
546
+ debitOutputWork();
547
+ prepareTrustedOutputPayload(budget, key);
548
+ wireKeys.add(key);
549
+ defineTrustedOutputValue(output, key, value2);
550
+ };
551
+ const prepareWire = (input, current, level, observeHook = true, entered = false, documentRoot = false, slots = 1) => {
552
+ if (!entered) visitTrustedOutput(budget, level, slots);
553
+ if (typeof input === "function" || typeof input === "symbol") authorizationError("unsupported selected BSON value");
554
+ if (input === null || typeof input !== "object") {
555
+ if (typeof input === "string") prepareTrustedOutputPayload(budget, input);
556
+ return input;
557
+ }
558
+ if (import_node_util3.types.isProxy(input)) authorizationError("unsupported selected proxy");
559
+ if (!entered && active.has(input)) authorizationError("cyclic selected output");
560
+ if (!entered) active.add(input);
561
+ try {
562
+ const hook = selectedDataProperty(input, "toBSON");
563
+ if (typeof hook === "function") {
564
+ if (!observeHook) authorizationError("chained selected BSON hooks");
565
+ const normalized = outsideOutputWorkLedger(() => Reflect.apply(hook, input, []));
566
+ if (normalized !== input) return prepareWire(normalized, current, level, false, false, documentRoot);
567
+ }
568
+ if (isBsonValue(input)) {
569
+ if (documentRoot) authorizationError("unsupported selected BSON document");
570
+ let prototype2 = input;
571
+ for (let hops = 0; prototype2 && !bsonFamilies.has(prototype2) && hops <= 100; hops++) {
572
+ if (import_node_util3.types.isProxy(prototype2)) authorizationError("unsupported selected proxy");
573
+ if (Object.hasOwn(prototype2, "_bsontype") || Object.hasOwn(prototype2, /* @__PURE__ */ Symbol.for("@@mdb.bson.type")))
574
+ authorizationError("overridden selected BSON brand");
575
+ prototype2 = Object.getPrototypeOf(prototype2);
576
+ }
577
+ if (!prototype2 || !bsonFamilies.has(prototype2)) authorizationError("unsupported selected BSON family");
578
+ const family = bsonFamilies.get(prototype2);
579
+ const output2 = Object.create(prototype2);
580
+ Object.defineProperty(output2, "toBSON", { value: void 0 });
581
+ const field = (key, type) => {
582
+ const value2 = selectedDataProperty(input, key, true);
583
+ if (typeof value2 !== type) authorizationError("unsupported selected BSON state");
584
+ if (typeof value2 === "string") prepareTrustedOutputPayload(budget, value2);
585
+ defineWireValue(output2, key, value2);
586
+ return value2;
587
+ };
588
+ const bytes = (key, length) => {
589
+ const value2 = selectedBsonBytes(selectedDataProperty(input, key, true), budget);
590
+ if (length !== void 0 && value2.length !== length) authorizationError("invalid selected BSON bytes");
591
+ defineWireValue(output2, key, value2);
592
+ };
593
+ const method = (key) => {
594
+ if (selectedDataProperty(input, key) !== selectedDataProperty(prototype2, key))
595
+ authorizationError("unsupported selected BSON serializer override");
596
+ };
597
+ const document = (key) => {
598
+ const raw = selectedDataProperty(input, key, true);
599
+ const value2 = prepareWire(raw, prepareOutputWorkString([current, key]), level + 1, true, false, true);
600
+ if (!value2 || typeof value2 !== "object" || !Array.isArray(value2) && Object.getPrototypeOf(value2) !== null)
601
+ authorizationError("unsupported selected BSON document");
602
+ defineWireValue(output2, key, value2);
603
+ };
604
+ switch (family) {
605
+ case "Code": {
606
+ field("code", "string");
607
+ const scope = selectedDataProperty(input, "scope", true);
608
+ if (scope != null) document("scope");
609
+ else defineWireValue(output2, "scope", scope);
610
+ break;
611
+ }
612
+ case "DBRef": {
613
+ field("collection", "string");
614
+ const db = selectedDataProperty(input, "db", true);
615
+ if (db != null) field("db", "string");
616
+ defineWireValue(
617
+ output2,
618
+ "oid",
619
+ prepareWire(
620
+ selectedDataProperty(input, "oid", true),
621
+ prepareOutputWorkString([current, "oid"]),
622
+ level + 1
623
+ )
624
+ );
625
+ document("fields");
626
+ const ordered = /* @__PURE__ */ Object.create(null);
627
+ defineWireValue(ordered, "$ref", output2.collection);
628
+ defineWireValue(ordered, "$id", output2.oid);
629
+ if (db != null) defineWireValue(ordered, "$db", output2.db);
630
+ for (const key of Object.keys(output2.fields))
631
+ defineWireValue(ordered, key, output2.fields[key]);
632
+ return ordered;
633
+ }
634
+ case "ObjectId":
635
+ method("serializeInto");
636
+ if (Object.hasOwn(input, "buffer"))
637
+ bytes("buffer", 12);
638
+ else for (const key of ["i0", "i1", "i2", "i3"]) field(key, "number");
639
+ break;
640
+ case "Timestamp":
641
+ case "Long":
642
+ method("getLowBits");
643
+ method("getHighBits");
644
+ field("low", "number");
645
+ field("high", "number");
646
+ field("unsigned", "boolean");
647
+ break;
648
+ case "Decimal128":
649
+ bytes("bytes", 16);
650
+ break;
651
+ case "Binary": {
652
+ bytes("buffer");
653
+ const position = field("position", "number");
654
+ const subtype = field("sub_type", "number");
655
+ if (!Number.isInteger(position) || position < 0 || position > output2.buffer.length || !Number.isInteger(subtype) || subtype < 0 || subtype > 255)
656
+ authorizationError("invalid selected BSON binary");
657
+ break;
658
+ }
659
+ case "Int32":
660
+ method("valueOf");
661
+ field("value", "number");
662
+ break;
663
+ case "Double":
664
+ field("value", "number");
665
+ break;
666
+ case "BSONSymbol":
667
+ field("value", "string");
668
+ break;
669
+ case "BSONRegExp":
670
+ field("pattern", "string");
671
+ field("options", "string");
672
+ break;
673
+ }
674
+ return output2;
675
+ }
676
+ if (selectedDataProperty(input, "_bsontype") != null) authorizationError("unsupported selected BSON tag");
677
+ const noHook = (value2) => {
678
+ Object.defineProperty(value2, "toBSON", { value: void 0 });
679
+ return value2;
680
+ };
681
+ if (import_node_util3.types.isDate(input)) {
682
+ const getTime = selectedDataProperty(input, "getTime");
683
+ if (typeof getTime !== "function") authorizationError("unsupported selected BSON date");
684
+ const time = outsideOutputWorkLedger(() => Reflect.apply(getTime, input, []));
685
+ if (typeof time !== "number") authorizationError("unsupported selected BSON date");
686
+ prepareTrustedOutputPayload(budget, 8);
687
+ return noHook(new Date(time));
688
+ }
689
+ if (import_node_util3.types.isUint8Array(input)) return noHook(selectedBsonBytes(input, budget));
690
+ if (import_node_util3.types.isRegExp(input)) {
691
+ const source = Object.getOwnPropertyDescriptor(RegExp.prototype, "source").get.call(input);
692
+ prepareTrustedOutputPayload(budget, source);
693
+ const flags = prepareRegExpFlags(input, budget);
694
+ prepareTrustedOutputPayload(budget, flags);
695
+ return noHook(new RegExp(source, flags));
696
+ }
697
+ const output = /* @__PURE__ */ Object.create(null);
698
+ if (import_node_util3.types.isMap(input)) {
699
+ for (const [key, entry] of Map.prototype.entries.call(input)) {
700
+ visitTrustedOutput(budget, level + 1);
701
+ if (typeof key !== "string") authorizationError("selected Map requires string keys");
702
+ if (protectedValueKeys.has(key)) {
703
+ if (policy.rejectProtectedKeys) authorizationError("protected native snapshot key");
704
+ continue;
705
+ }
706
+ const child = prepareOutputWorkString([current, key]);
707
+ if (!policy.keep(key, child)) continue;
708
+ prepareTrustedOutputPayload(budget, key);
709
+ defineWireValue(output, key, prepareWire(entry, child, level + 1));
710
+ }
711
+ return output;
712
+ }
713
+ const array = Array.isArray(input);
714
+ const prototype = Object.getPrototypeOf(input);
715
+ if (!array && prototype !== Object.prototype && prototype !== null)
716
+ authorizationError("unsupported selected object");
717
+ const container = array ? noHook([]) : output;
718
+ if (array) {
719
+ const length = Object.getOwnPropertyDescriptor(input, "length").value;
720
+ if (length) visitTrustedOutput(budget, level + 1, length);
721
+ container.length = length;
722
+ for (let index = 0; index < length; index++) defineWireValue(container, String(index), void 0);
723
+ }
724
+ for (const key of Reflect.ownKeys(input)) {
725
+ if (array && key === "length") continue;
726
+ visitTrustedOutput(budget, level + 1);
727
+ if (typeof key !== "string") authorizationError("symbol selected output key");
728
+ if (protectedValueKeys.has(key)) {
729
+ if (policy.rejectProtectedKeys) authorizationError("protected native snapshot key");
730
+ continue;
731
+ }
732
+ if (key === "toBSON" && (array || typeof hook === "function")) continue;
733
+ if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid selected array property");
734
+ const child = array ? current : prepareOutputWorkString([current, key]);
735
+ if (!array && !policy.keep(key, child)) continue;
736
+ prepareTrustedOutputPayload(budget, key);
737
+ const slot = Object.getOwnPropertyDescriptor(input, key);
738
+ if (!("value" in slot) || !slot.enumerable) authorizationError("accessor/non-enumerable selected value");
739
+ defineWireValue(container, key, prepareWire(slot.value, child, level + 1, true, false, false, 0));
740
+ }
741
+ return container;
742
+ } finally {
743
+ if (!entered) active.delete(input);
744
+ }
745
+ };
746
+ const prepared = prepareWire(value, path, depth, true, true);
747
+ assertTrustedOutputBudget(budget);
748
+ for (const key of wireKeys) {
749
+ const slot = Object.getOwnPropertyDescriptor(Object.prototype, key);
750
+ if (slot && !("value" in slot)) authorizationError("inherited accessor selected BSON output");
751
+ }
752
+ const wrapper = /* @__PURE__ */ Object.create(null);
753
+ defineTrustedOutputValue(wrapper, "value", prepared);
754
+ const result = outsideOutputWorkLedger(
755
+ () => import_mongoose.mongo.BSON.deserialize(import_mongoose.mongo.BSON.serialize(wrapper), { promoteValues: false, bsonRegExp: true }).value
756
+ );
757
+ assertTrustedOutputBudget(budget);
758
+ return result;
759
+ }
760
+ function materializeTrustedOutputValue(value, path, budget, policy, depth = 0, prepaid = false) {
761
+ const ledger = budgets.get(budget)?.ledger;
762
+ if (ledger && currentOutputWorkLedger() !== ledger)
763
+ return withOutputWorkLedger(
764
+ ledger,
765
+ () => materializeTrustedOutputValue(value, path, budget, policy, depth, prepaid)
766
+ );
767
+ if (value === null || typeof value !== "object" && typeof value !== "function" && typeof value !== "symbol") {
768
+ try {
769
+ visitTrustedOutput(budget, depth, prepaid ? 0 : 1);
770
+ if (typeof value === "string") prepareTrustedOutputPayload(budget, value);
771
+ assertTrustedOutputBudget(budget);
772
+ return value;
773
+ } catch (error) {
774
+ failTrustedOutputBudget(budget, error);
775
+ }
776
+ }
777
+ const active = /* @__PURE__ */ new WeakSet();
778
+ const visit = (input, current, level, slots = 1) => {
779
+ visitTrustedOutput(budget, level, slots);
780
+ if (typeof input === "function" || typeof input === "symbol") authorizationError("unsupported selected value");
781
+ if (input === null || typeof input !== "object") {
782
+ if (typeof input === "string") prepareTrustedOutputPayload(budget, input);
783
+ return input;
784
+ }
785
+ if (import_node_util3.types.isProxy(input)) authorizationError("unsupported selected proxy");
786
+ if (active.has(input)) authorizationError("cyclic selected output");
787
+ active.add(input);
788
+ try {
789
+ if (import_node_util3.types.isDate(input)) {
790
+ const method = selectedDataProperty(input, "getTime");
791
+ if (typeof method !== "function") authorizationError("unsupported selected date");
792
+ const time = outsideOutputWorkLedger(() => Reflect.apply(method, input, []));
793
+ if (typeof time !== "number") authorizationError("unsupported selected date");
794
+ prepareTrustedOutputPayload(budget, 8);
795
+ return new Date(time);
796
+ }
797
+ if (Buffer.isBuffer(input)) return selectedBsonBytes(input, budget);
798
+ if (import_node_util3.types.isRegExp(input)) {
799
+ const source = Object.getOwnPropertyDescriptor(RegExp.prototype, "source").get.call(input);
800
+ prepareTrustedOutputPayload(budget, source);
801
+ const flags = prepareRegExpFlags(input, budget);
802
+ prepareTrustedOutputPayload(budget, flags);
803
+ const output2 = new RegExp(source, flags);
804
+ const lastIndex = selectedDataProperty(input, "lastIndex", true);
805
+ if (typeof lastIndex !== "number") authorizationError("unsupported selected regexp");
806
+ output2.lastIndex = lastIndex;
807
+ return output2;
808
+ }
809
+ if (isBsonValue(input)) {
810
+ try {
811
+ return copyTrustedBsonValue(input, current, budget, policy, level, active);
812
+ } catch (error) {
813
+ if (error instanceof ServiceAuthorizationError) throw error;
814
+ authorizationError("unsupported selected BSON value");
815
+ }
816
+ }
817
+ if (import_node_util3.types.isMap(input)) {
818
+ const output2 = {};
819
+ for (const [key, entry] of Map.prototype.entries.call(input)) {
820
+ visitTrustedOutput(budget, level + 1);
821
+ if (typeof key !== "string") authorizationError("selected Map requires string keys");
822
+ if (protectedValueKeys.has(key)) {
823
+ if (policy.rejectProtectedKeys) authorizationError("protected native snapshot key");
824
+ continue;
825
+ }
826
+ const child = prepareOutputWorkString([current, key]);
827
+ if (!policy.keep(key, child)) continue;
828
+ prepareTrustedOutputPayload(budget, key);
829
+ defineTrustedOutputValue(output2, key, visit(entry, child, level + 1));
830
+ }
831
+ return output2;
832
+ }
833
+ const array = Array.isArray(input);
834
+ const prototype = Object.getPrototypeOf(input);
835
+ if (!array && prototype !== Object.prototype && prototype !== null)
836
+ authorizationError("unsupported selected object");
837
+ const output = array ? [] : {};
838
+ if (array) {
839
+ const length = Object.getOwnPropertyDescriptor(input, "length").value;
840
+ if (length) visitTrustedOutput(budget, level + 1, length);
841
+ output.length = length;
842
+ }
843
+ for (const key of Reflect.ownKeys(input)) {
844
+ if (array && key === "length") continue;
845
+ visitTrustedOutput(budget, level + 1);
846
+ if (typeof key !== "string") authorizationError("symbol selected output key");
847
+ if (protectedValueKeys.has(key)) {
848
+ if (policy.rejectProtectedKeys) authorizationError("protected native snapshot key");
849
+ continue;
850
+ }
851
+ if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid selected array property");
852
+ const child = array ? current : prepareOutputWorkString([current, key]);
853
+ if (!array && !policy.keep(key, child)) continue;
854
+ prepareTrustedOutputPayload(budget, key);
855
+ const slot = Object.getOwnPropertyDescriptor(input, key);
856
+ if (isGeneratedPermissionsAliasSlot(input, key, slot)) continue;
857
+ if (!("value" in slot) || !slot.enumerable) authorizationError("accessor/non-enumerable selected value");
858
+ defineTrustedOutputValue(output, key, visit(slot.value, child, level + 1, 0));
859
+ }
860
+ return copyPermissionsAlias(input, output);
861
+ } catch (error) {
862
+ failTrustedOutputBudget(budget, error);
863
+ } finally {
864
+ active.delete(input);
865
+ }
866
+ };
867
+ try {
868
+ const result = visit(value, path, depth, prepaid ? 0 : 1);
869
+ assertTrustedOutputBudget(budget);
870
+ return result;
871
+ } catch (error) {
872
+ failTrustedOutputBudget(budget, error);
873
+ }
874
+ }
875
+
876
+ // src/acl/authorization-snapshot.ts
877
+ var ServiceAuthorizationError = class extends import_express_json_router.default.clientErrors.BadRequestError {
878
+ constructor(detail) {
879
+ const errors = [{ detail: `Service authorization: ${detail}` }];
880
+ super("Bad Request", { errors });
881
+ this.result = { success: false, kind: "error", code: "bad_request" /* BadRequest */, errors };
882
+ Object.freeze(errors[0]);
883
+ Object.freeze(errors);
884
+ Object.freeze(this.result);
885
+ Object.defineProperty(this, "result", {
886
+ value: this.result,
887
+ enumerable: true,
888
+ writable: false,
889
+ configurable: false
890
+ });
891
+ }
892
+ };
893
+ function authorizationError(detail) {
894
+ throw new ServiceAuthorizationError(detail);
895
+ }
896
+ var unsafeKeys2 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
897
+ function authorizationRecord(value, label) {
898
+ if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
899
+ authorizationError(`${label} must be a plain object`);
900
+ }
901
+ return value;
902
+ }
903
+ function copyAuthorizationValue(value, configuration = false) {
904
+ const active = /* @__PURE__ */ new WeakSet();
905
+ const budget = createTrustedOutputBudget();
906
+ function copy(input, depth) {
907
+ visitTrustedOutput(budget, depth);
908
+ if (typeof input === "function") {
909
+ if (configuration === true) return input;
910
+ authorizationError("functions are not policy values");
911
+ }
912
+ if (typeof input === "symbol") authorizationError("symbols are not policy values");
913
+ if (input === null || typeof input !== "object") {
914
+ if (typeof input === "string") prepareTrustedOutputPayload(budget, input);
915
+ return input;
916
+ }
917
+ if (import_node_util4.types.isProxy(input)) authorizationError("proxy snapshot input");
918
+ const ownedCatalog = configuration === true ? readOwnedAuthorizationCatalogWork(input) : void 0;
919
+ if (ownedCatalog) {
920
+ preloadTrustedOutputBudget(budget, depth + ownedCatalog.depth, ownedCatalog.slots - 1);
921
+ return input;
922
+ }
923
+ if (active.has(input)) authorizationError("cyclic input");
924
+ active.add(input);
925
+ try {
926
+ if (input instanceof Date) {
927
+ const time = outsideOutputWorkLedger(() => input.getTime());
928
+ prepareTrustedOutputPayload(budget, 8);
929
+ return outsideOutputWorkLedger(() => new Date(time));
930
+ }
931
+ if (Buffer.isBuffer(input)) {
932
+ if (!currentOutputWorkLedger()) return Buffer.from(input);
933
+ const normalized = outsideOutputWorkLedger(() => Buffer.from(input));
934
+ return materializeTrustedOutputValue(normalized, "", budget, { keep: () => true }, depth, true);
935
+ }
936
+ if (input instanceof RegExp) {
937
+ const result2 = outsideOutputWorkLedger(() => new RegExp(input.source, input.flags));
938
+ result2.lastIndex = input.lastIndex;
939
+ return currentOutputWorkLedger() ? materializeTrustedOutputValue(result2, "", budget, { keep: () => true }, depth, true) : result2;
940
+ }
941
+ if (input instanceof import_mongoose2.mongo.BSON.BSONValue) {
942
+ try {
943
+ return materializeTrustedOutputValue(
944
+ input,
945
+ "",
946
+ budget,
947
+ { keep: () => true, rejectProtectedKeys: true },
948
+ depth,
949
+ true
950
+ );
951
+ } catch (error) {
952
+ if (error instanceof ServiceAuthorizationError) throw error;
953
+ authorizationError("unsupported BSON snapshot");
954
+ }
955
+ }
956
+ if (configuration && input instanceof Map) {
957
+ const result2 = /* @__PURE__ */ new Map();
958
+ for (const [key, entry] of Map.prototype.entries.call(input))
959
+ result2.set(copy(key, depth + 1), copy(entry, depth + 1));
960
+ return result2;
961
+ }
962
+ if (configuration && input instanceof Set) {
963
+ const result2 = /* @__PURE__ */ new Set();
964
+ for (const entry of Set.prototype.values.call(input)) result2.add(copy(entry, depth + 1));
965
+ return result2;
966
+ }
967
+ const array = Array.isArray(input);
968
+ if (array && input.length > 2e4) authorizationError("snapshot array exceeds structural limits");
969
+ if (!array) authorizationRecord(input, "snapshot");
970
+ const result = array ? [] : {};
971
+ let definedProperty = false;
972
+ for (const key of Reflect.ownKeys(input)) {
973
+ if (array && key === "length") continue;
974
+ if (typeof key !== "string" || unsafeKeys2.has(key)) authorizationError("unsafe snapshot key");
975
+ prepareTrustedOutputPayload(budget, key);
976
+ if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid array property");
977
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
978
+ if (!("value" in descriptor) || !descriptor.enumerable && configuration !== "document")
979
+ authorizationError("accessor/non-enumerable input");
980
+ const value2 = copy(descriptor.value, depth + 1);
981
+ if (array || definedProperty && Object.getPrototypeOf(result) !== Object.prototype || key in result) {
982
+ definedProperty = true;
983
+ Object.defineProperty(result, key, {
984
+ value: value2,
985
+ enumerable: true,
986
+ writable: true,
987
+ configurable: true
988
+ });
989
+ } else result[key] = value2;
990
+ }
991
+ if (array) result.length = input.length;
992
+ return Object.freeze(result);
993
+ } finally {
994
+ active.delete(input);
995
+ }
996
+ }
997
+ return copy(value, 0);
998
+ }
999
+
1000
+ // src/acl/output-work-ledger.ts
1001
+ var preparation = new import_node_async_hooks.AsyncLocalStorage();
1002
+ function currentOutputWorkLedger() {
1003
+ return preparation.getStore();
1004
+ }
1005
+ function withOutputWorkLedger(ledger, run) {
1006
+ if (preparation.getStore() === ledger) return run();
1007
+ return preparation.run(ledger, run);
1008
+ }
1009
+ function outsideOutputWorkLedger(run) {
1010
+ if (!preparation.getStore()) return run();
1011
+ return preparation.run(void 0, run);
1012
+ }
1013
+ function debitOutputWork(ledger = currentOutputWorkLedger(), units = 1) {
1014
+ if (!ledger) return;
1015
+ ledger.check();
1016
+ if (ledger.failure) throw ledger.failure;
1017
+ if (!Number.isSafeInteger(units) || units < 0 || ledger.work + units > 2e5) {
1018
+ ledger.failure ??= new ServiceAuthorizationError("collection output exceeds aggregate work limit");
1019
+ ledger.fail(ledger.failure);
1020
+ throw ledger.failure;
1021
+ }
1022
+ ledger.work += units;
1023
+ }
1024
+ function debitOutputPayload(ledger, value) {
1025
+ if (!ledger) return;
1026
+ ledger.check();
1027
+ if (ledger.failure) throw ledger.failure;
1028
+ const bytes = typeof value === "string" ? Buffer.byteLength(value, "utf8") : value;
1029
+ if (!Number.isSafeInteger(bytes) || bytes < 0 || ledger.payload + bytes > 16 * 1024 * 1024) {
1030
+ ledger.failure ??= new ServiceAuthorizationError("collection output exceeds payload limit");
1031
+ ledger.fail(ledger.failure);
1032
+ throw ledger.failure;
1033
+ }
1034
+ ledger.payload += bytes;
1035
+ }
1036
+ function prepareOutputWorkString(parts, separator = ".", ledger = currentOutputWorkLedger()) {
1037
+ if (ledger) {
1038
+ const bytes = parts.reduce((sum, part) => sum + Buffer.byteLength(part, "utf8"), 0) + Math.max(0, parts.length - 1) * Buffer.byteLength(separator, "utf8");
1039
+ debitOutputPayload(ledger, bytes);
1040
+ }
1041
+ return parts.join(separator);
1042
+ }
1043
+
1044
+ // src/acl/authorization-modes.ts
1045
+ var import_node_util5 = require("util");
1046
+ var retiredAuthorizationOptions = [
1047
+ "unsafeSkipListDocumentSnapshotChecks",
1048
+ "unsafeSkipReadDocumentSnapshotChecks",
1049
+ "unsafeSkipListOutputSnapshotChecks",
1050
+ "unsafeSkipReadOutputSnapshotChecks",
1051
+ "unsafeSkipListNestedDocumentSnapshotChecks",
1052
+ "unsafeSkipReadNestedDocumentSnapshotChecks",
1053
+ "unsafeSkipListInitialOutputSnapshotCopy",
1054
+ "unsafeSkipReadInitialOutputSnapshotCopy",
1055
+ "unsafeUseListAuthorizationFastPath",
1056
+ "unsafeUseReadAuthorizationFastPath"
1057
+ ];
1058
+ var authorizationModeKeys = [
1059
+ "readAuthorizationMode",
1060
+ "listAuthorizationMode",
1061
+ "createAuthorizationMode",
1062
+ "updateAuthorizationMode"
1063
+ ];
1064
+ var authorizationModeOperations = {
1065
+ readAuthorizationMode: "read",
1066
+ listAuthorizationMode: "list",
1067
+ createAuthorizationMode: "create",
1068
+ updateAuthorizationMode: "update"
1069
+ };
1070
+ var serverAuthorizationControls = [...retiredAuthorizationOptions, ...authorizationModeKeys];
1071
+ function authorizationControlError(key) {
1072
+ return retiredAuthorizationOptions.includes(key) ? `${key} was removed; migrate to readAuthorizationMode/listAuthorizationMode on server model/default-model options` : `${key} is server model/default-model configuration only`;
1073
+ }
1074
+ function normalizeAuthorizationMode(value) {
1075
+ if (value === void 0) return void 0;
1076
+ if (value === "isolated" || value === "trusted") return value;
1077
+ throw new TypeError(
1078
+ "Authorization mode must be the literal isolated or trusted, or undefined to restore inheritance"
1079
+ );
1080
+ }
1081
+ function assertAuthorizationModeKey(key, model) {
1082
+ if (typeof key !== "string") throw new TypeError("Configuration option key must be a string");
1083
+ const root = key.split(".")[0];
1084
+ if (retiredAuthorizationOptions.includes(root))
1085
+ throw new TypeError(authorizationControlError(root));
1086
+ if (authorizationModeKeys.includes(root) && (!model || key !== root))
1087
+ throw new TypeError(
1088
+ !model ? authorizationControlError(root) : `${root} is a scalar mode; dotted setters are unsupported`
1089
+ );
1090
+ }
1091
+ function admitControlPrototypes(value, reject) {
1092
+ const owners = [];
1093
+ for (let owner = value; owner; owner = Object.getPrototypeOf(owner)) {
1094
+ if (import_node_util5.types.isProxy(owner)) reject("Proxy control/configuration prototype is unsupported");
1095
+ if (owners.length > 100) reject("Control/configuration prototype depth exceeded");
1096
+ owners.push(owner);
1097
+ }
1098
+ return owners;
1099
+ }
1100
+ function controlPropertyKeys(owners, reject) {
1101
+ const keys2 = /* @__PURE__ */ new Set();
1102
+ for (const owner of owners) {
1103
+ for (const key of Reflect.ownKeys(owner)) {
1104
+ if (typeof key === "string") keys2.add(key);
1105
+ if (keys2.size > 2e4) reject("Control/configuration keys exceed structural limits");
1106
+ }
1107
+ }
1108
+ return [...keys2];
1109
+ }
1110
+ function assertAuthorizationModeOptions(value, model) {
1111
+ const reject = (detail) => {
1112
+ throw new TypeError(detail);
1113
+ };
1114
+ if (!value || typeof value !== "object" || Array.isArray(value))
1115
+ throw new TypeError("Authorization configuration must be an options object");
1116
+ const owners = admitControlPrototypes(value, reject);
1117
+ for (const key of controlPropertyKeys(owners, reject)) {
1118
+ assertAuthorizationModeKey(key, model);
1119
+ if (!authorizationModeKeys.includes(key)) continue;
1120
+ const slot = Object.getOwnPropertyDescriptor(value, key);
1121
+ if (!slot || !("value" in slot) || !slot.enumerable)
1122
+ throw new TypeError(`${key} must be an own enumerable data option`);
1123
+ normalizeAuthorizationMode(slot.value);
1124
+ }
1125
+ }
1126
+
1127
+ // src/validation/public-admission.ts
1128
+ var privateControls = [
1129
+ "authorization",
1130
+ "overrides",
1131
+ "documentAuthorization",
1132
+ "documentAuthorizationStage",
1133
+ "execution",
1134
+ "executionContext",
1135
+ "serviceExecutionContext",
1136
+ "snapshotDerivation",
1137
+ "resolvedAuthorization",
1138
+ "preparedQuery",
1139
+ "preparedFilter",
1140
+ "preparedModelQuery",
1141
+ "resolvedIdentifier",
1142
+ "skipParsing",
1143
+ "skipAuthorization",
1144
+ "alreadyAuthorized",
1145
+ ...serverAuthorizationControls,
1146
+ "operation"
1147
+ ];
1148
+ var PublicAdmissionError = class extends import_express_json_router2.default.clientErrors.BadRequestError {
1149
+ constructor(detail) {
1150
+ const errors = [{ detail }];
1151
+ super("Bad Request", { errors });
1152
+ this.result = { success: false, kind: "error", code: "bad_request" /* BadRequest */, errors };
1153
+ }
1154
+ };
1155
+ var defaultControlBuckets = [
1156
+ "findOneArgs",
1157
+ "findOneOptions",
1158
+ "findByIdArgs",
1159
+ "findByIdOptions",
1160
+ "findArgs",
1161
+ "findOptions",
1162
+ "createArgs",
1163
+ "createOptions",
1164
+ "updateOneArgs",
1165
+ "updateOneOptions",
1166
+ "upsertOptions",
1167
+ "updateByIdArgs",
1168
+ "upsertArgs",
1169
+ "updateByIdOptions",
1170
+ "existsOptions",
1171
+ "publicListArgs",
1172
+ "publicListOptions",
1173
+ "publicCreateArgs",
1174
+ "publicCreateOptions",
1175
+ "publicReadArgs",
1176
+ "publicReadOptions",
1177
+ "publicUpdateArgs",
1178
+ "publicUpdateOptions"
1179
+ ];
1180
+ function assertPublicAdmission(input, kind = "envelope") {
1181
+ assertPublicControlAdmission(input, kind);
1182
+ }
1183
+ function assertPublicControlAdmission(input, kind) {
1184
+ walkControlAdmission(
1185
+ input,
1186
+ kind,
1187
+ (_record, path, keys2) => {
1188
+ for (const property of keys2) {
1189
+ const key = property.split(".")[0];
1190
+ if (privateControls.includes(key)) {
1191
+ throw new PublicAdmissionError(
1192
+ serverAuthorizationControls.includes(key) ? `Unsupported public control ${path}.${authorizationControlError(key)}` : `Unsupported public control ${path}.${key}; use explicit per-call internal service options for backend authorization`
1193
+ );
1194
+ }
1195
+ }
1196
+ },
1197
+ (detail) => {
1198
+ throw new PublicAdmissionError(detail);
1199
+ }
1200
+ );
1201
+ }
1202
+ function assertNoServerModelControls(input, reject, kind = "envelope") {
1203
+ walkControlAdmission(
1204
+ input,
1205
+ kind,
1206
+ (_record, path, keys2) => {
1207
+ for (const property of keys2) {
1208
+ const key = property.split(".")[0];
1209
+ if (serverAuthorizationControls.includes(key))
1210
+ reject(`${path}.${authorizationControlError(key)}`);
1211
+ if (key === "documentAuthorization" || key === "documentAuthorizationStage")
1212
+ reject(`${path}.${key} was removed; output DTOs carry no authority`);
1213
+ }
1214
+ },
1215
+ reject
1216
+ );
1217
+ }
1218
+ function walkControlAdmission(input, kind, check, reject) {
1219
+ const pending = [{ value: input, kind, path: "request", depth: 0 }];
1220
+ const seen = /* @__PURE__ */ new WeakMap();
1221
+ let slots = 1;
1222
+ while (pending.length) {
1223
+ debitOutputWork();
1224
+ const { value, kind: slot, path, depth } = pending.pop();
1225
+ if (!value || typeof value !== "object" && typeof value !== "function") continue;
1226
+ if (typeof value === "function" && (slot === "policy" || slot === "data")) continue;
1227
+ if (import_node_util6.types.isProxy(value)) reject(`unsupported proxy in control admission: ${path}`);
1228
+ const owners = admitControlPrototypes(value, reject);
1229
+ const kinds = seen.get(value) ?? /* @__PURE__ */ new Set();
1230
+ if (kinds.has(slot)) continue;
1231
+ kinds.add(slot);
1232
+ seen.set(value, kinds);
1233
+ const add = (child, childKind, key) => {
1234
+ if (child === void 0 || child === null) return;
1235
+ if (++slots > 2e4 || depth >= 100) reject("control admission exceeds structural limits");
1236
+ pending.push({ value: child, kind: childKind, path: `${path}.${key}`, depth: depth + 1 });
1237
+ };
1238
+ const record2 = value;
1239
+ const propertyKeys = slot === "data" || slot === "policies" ? [] : controlPropertyKeys(owners, reject);
1240
+ debitOutputWork(void 0, propertyKeys.length);
1241
+ if (slot !== "data" && slot !== "policies" && slot !== "model-options") check(record2, path, propertyKeys);
1242
+ for (const property of propertyKeys) {
1243
+ const parts = property.split(".");
1244
+ if (parts.length < 2 || !parts.some((part) => serverAuthorizationControls.includes(part)))
1245
+ continue;
1246
+ const roots = slot === "defaults" ? defaultControlBuckets : slot === "policy" ? ["rows", "outputFields", "inputFields", "operation", "related"] : ["args", "options", "sqOptions", "include", "populate", "authorization", "defaults"];
1247
+ if (!roots.includes(parts[0])) continue;
1248
+ if (parts.length > 100) reject("control admission dotted path exceeds structural limits");
1249
+ const wrapper = {};
1250
+ let target = wrapper;
1251
+ for (const part of parts.slice(0, -1)) {
1252
+ const child = {};
1253
+ Object.defineProperty(target, part, { value: child, enumerable: true });
1254
+ target = child;
1255
+ }
1256
+ const descriptor = owners.map((owner) => Object.getOwnPropertyDescriptor(owner, property)).find(Boolean);
1257
+ Object.defineProperty(target, parts.at(-1), descriptor);
1258
+ add(wrapper, slot, property);
1259
+ }
1260
+ const read = (key) => {
1261
+ for (const owner of owners) {
1262
+ const descriptor = Object.getOwnPropertyDescriptor(owner, key);
1263
+ if (!descriptor) continue;
1264
+ if (!("value" in descriptor)) reject(`accessor control/data property: ${path}.${key}`);
1265
+ return descriptor.value;
1266
+ }
1267
+ return void 0;
1268
+ };
1269
+ if (Array.isArray(value)) {
1270
+ if (value.length > 2e4) reject("control admission array exceeds structural limits");
1271
+ for (let index = 0; index < value.length; index++) {
1272
+ if (index in value) add(read(String(index)), slot, String(index));
1273
+ }
1274
+ continue;
1275
+ }
1276
+ if (slot === "data") {
1277
+ if (!(0, import_utils2.isPlainObject)(value)) continue;
1278
+ add(read("$$sq"), "envelope", "$$sq");
1279
+ for (const key of Object.keys(value)) if (key !== "$$sq") add(read(key), "data", key);
1280
+ continue;
1281
+ }
1282
+ if (slot === "defaults") {
1283
+ const keys2 = /* @__PURE__ */ new Set([...Object.keys(value), ...defaultControlBuckets]);
1284
+ if (keys2.size > 2e4) reject("control admission defaults exceeds structural limits");
1285
+ for (const key of keys2) if (key in record2) add(read(key), "envelope", key);
1286
+ continue;
1287
+ }
1288
+ add(read("defaults"), "defaults", "defaults");
1289
+ if (slot === "policies") {
1290
+ for (const key of Object.keys(value)) add(read(key), "policy", key);
1291
+ continue;
1292
+ }
1293
+ if (slot === "policy") {
1294
+ for (const key of ["rows", "outputFields", "inputFields", "operation", "parent", "child", "visibility"])
1295
+ add(read(key), "policy", key);
1296
+ add(read("related"), "policies", "related");
1297
+ add(read("filter"), "data", "filter");
1298
+ continue;
1299
+ }
1300
+ for (const key of ["args", "options", "sqOptions"]) add(read(key), "envelope", key);
1301
+ add(read("include"), "include", "include");
1302
+ add(read("populate"), "populate", "populate");
1303
+ add(read("authorization"), "policy", "authorization");
1304
+ add(read("operationAccess"), "policy", "operationAccess");
1305
+ for (const key of slot === "data-options" ? ["filter", "match"] : ["filter", "match", "data"])
1306
+ add(read(key), "data", key);
1307
+ }
1308
+ }
1309
+ function assertHydrationDefaults(defaults2) {
1310
+ if (defaults2 && typeof defaults2 === "object") {
1311
+ const record2 = defaults2;
1312
+ if ("hydration" in record2)
1313
+ throw new TypeError("defaults.hydration is unsupported; use model hydration configuration");
1314
+ for (const bucket of [
1315
+ "publicListOptions",
1316
+ "publicReadOptions",
1317
+ "findOptions",
1318
+ "findOneOptions",
1319
+ "findByIdOptions",
1320
+ "createOptions",
1321
+ "updateOneOptions",
1322
+ "updateByIdOptions",
1323
+ "upsertOptions",
1324
+ "existsOptions",
1325
+ "publicCreateOptions",
1326
+ "publicUpdateOptions"
1327
+ ]) {
1328
+ const options = record2[bucket];
1329
+ if (!options || typeof options !== "object" && typeof options !== "function") continue;
1330
+ for (const key of ["lean", "hydration"]) {
1331
+ if (!(key in options)) continue;
1332
+ const method = bucket.slice(0, -"Options".length);
1333
+ const migration = ["publicList", "publicRead", "find", "findOne", "findById"].includes(method) ? `use model hydration.${method} ('lean' or 'hydrated')` : "this method has a fixed fetch mode";
1334
+ throw new TypeError(`defaults.${bucket}.${key} is unsupported; ${migration}`);
1335
+ }
1336
+ }
1337
+ }
1338
+ }
1339
+ function assertPublicDefaults(defaults2) {
1340
+ assertPublicControlAdmission(defaults2, "defaults");
1341
+ assertHydrationDefaults(defaults2);
1342
+ }
1343
+ var requestAuthorization = Object.freeze({ outputFields: Object.freeze({ mode: "request" }) });
1344
+
1345
+ // src/options/hydration.ts
1346
+ var methods = ["publicList", "publicRead", "find", "findOne", "findById"];
358
1347
  function normalizeHydration(value, path = "hydration") {
359
1348
  if (value === void 0) return void 0;
360
1349
  if (value === null || typeof value !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
@@ -406,15 +1395,15 @@ function assertNoGlobalPopulatePolicy(key) {
406
1395
 
407
1396
  // src/runtime.ts
408
1397
  var import_mongoose_schema_jsonschema = __toESM(require("mongoose-schema-jsonschema"));
409
- var import_utils13 = require("@web-ts-toolkit/utils");
1398
+ var import_utils14 = require("@web-ts-toolkit/utils");
410
1399
 
411
1400
  // src/helpers/query.ts
412
- var import_utils2 = require("@web-ts-toolkit/utils");
1401
+ var import_utils3 = require("@web-ts-toolkit/utils");
413
1402
  var DEFAULT_LIST_HARD_LIMIT = 1e3;
414
1403
  function normalizeSelect(select) {
415
- if (Array.isArray(select)) return (0, import_utils2.flattenDeep)(select.map(normalizeSelect));
416
- if ((0, import_utils2.isPlainObject)(select)) {
417
- return (0, import_utils2.reduce)(
1404
+ if (Array.isArray(select)) return (0, import_utils3.flattenDeep)(select.map(normalizeSelect));
1405
+ if ((0, import_utils3.isPlainObject)(select)) {
1406
+ return (0, import_utils3.reduce)(
418
1407
  select,
419
1408
  (ret, val, key) => {
420
1409
  if (val === 1) ret.push(key);
@@ -424,7 +1413,7 @@ function normalizeSelect(select) {
424
1413
  []
425
1414
  );
426
1415
  }
427
- if ((0, import_utils2.isString)(select))
1416
+ if ((0, import_utils3.isString)(select))
428
1417
  return String(select).split(/[\s,]+/).map((v) => v.trim()).filter(Boolean);
429
1418
  return [];
430
1419
  }
@@ -436,44 +1425,44 @@ function isValidFieldPath(field) {
436
1425
  }
437
1426
 
438
1427
  // src/helpers/index.ts
439
- var import_utils4 = require("@web-ts-toolkit/utils");
1428
+ var import_utils5 = require("@web-ts-toolkit/utils");
440
1429
 
441
1430
  // src/lib.ts
442
- var import_mongoose = require("mongoose");
443
- var import_utils3 = require("@web-ts-toolkit/utils");
444
- var isSchema = (val) => val instanceof import_mongoose.Schema;
445
- var isObjectIdType = (val) => val === "ObjectId" || val === import_mongoose.Schema.Types.ObjectId;
446
- var isReference = (val) => (0, import_utils3.isPlainObject)(val) && !!val.ref && isObjectIdType(val.type);
1431
+ var import_mongoose3 = require("mongoose");
1432
+ var import_utils4 = require("@web-ts-toolkit/utils");
1433
+ var isSchema = (val) => val instanceof import_mongoose3.Schema;
1434
+ var isObjectIdType = (val) => val === "ObjectId" || val === import_mongoose3.Schema.Types.ObjectId;
1435
+ var isReference = (val) => (0, import_utils4.isPlainObject)(val) && !!val.ref && isObjectIdType(val.type);
447
1436
 
448
1437
  // src/helpers/index.ts
449
1438
  function recurseObject(obj) {
450
1439
  if (isSchema(obj)) {
451
1440
  return buildRefs(obj.tree);
452
1441
  }
453
- if (!(0, import_utils4.isObject)(obj)) return null;
1442
+ if (!(0, import_utils5.isObject)(obj)) return null;
454
1443
  if (isReference(obj)) {
455
1444
  return obj.ref;
456
1445
  }
457
1446
  let ret = null;
458
- (0, import_utils4.forEach)(obj, (val) => {
1447
+ (0, import_utils5.forEach)(obj, (val) => {
459
1448
  ret = recurseObject(val);
460
- if (!(0, import_utils4.isEmpty)(ret)) {
1449
+ if (!(0, import_utils5.isEmpty)(ret)) {
461
1450
  return false;
462
1451
  }
463
1452
  });
464
1453
  return ret;
465
1454
  }
466
1455
  function buildRefs(schema) {
467
- if (!(0, import_utils4.isObject)(schema)) return {};
1456
+ if (!(0, import_utils5.isObject)(schema)) return {};
468
1457
  const references = {};
469
- (0, import_utils4.forEach)(schema, (val, key) => {
1458
+ (0, import_utils5.forEach)(schema, (val, key) => {
470
1459
  const paths = recurseObject(val);
471
- if (!(0, import_utils4.isEmpty)(paths)) {
1460
+ if (!(0, import_utils5.isEmpty)(paths)) {
472
1461
  references[key] = paths;
473
1462
  }
474
- const target = (0, import_utils4.isObject)(val) && "type" in val ? val.type ?? val : val;
475
- if ((0, import_utils4.isArray)(target) && target.length > 0) {
476
- if (isSchema(target[0]) || (0, import_utils4.isPlainObject)(target[0])) {
1463
+ const target = (0, import_utils5.isObject)(val) && "type" in val ? val.type ?? val : val;
1464
+ if ((0, import_utils5.isArray)(target) && target.length > 0) {
1465
+ if (isSchema(target[0]) || (0, import_utils5.isPlainObject)(target[0])) {
477
1466
  return;
478
1467
  }
479
1468
  }
@@ -481,12 +1470,12 @@ function buildRefs(schema) {
481
1470
  return references;
482
1471
  }
483
1472
  function buildSubPaths(schema) {
484
- if (!(0, import_utils4.isObject)(schema)) return [];
1473
+ if (!(0, import_utils5.isObject)(schema)) return [];
485
1474
  const subPaths = [];
486
- (0, import_utils4.forEach)(schema, (val, key) => {
487
- const target = (0, import_utils4.isObject)(val) && "type" in val ? val.type ?? val : val;
488
- if ((0, import_utils4.isArray)(target) && target.length > 0) {
489
- if (isSchema(target[0]) || (0, import_utils4.isPlainObject)(target[0]) && !isReference(target[0])) {
1475
+ (0, import_utils5.forEach)(schema, (val, key) => {
1476
+ const target = (0, import_utils5.isObject)(val) && "type" in val ? val.type ?? val : val;
1477
+ if ((0, import_utils5.isArray)(target) && target.length > 0) {
1478
+ if (isSchema(target[0]) || (0, import_utils5.isPlainObject)(target[0]) && !isReference(target[0])) {
490
1479
  subPaths.push(key);
491
1480
  }
492
1481
  }
@@ -495,7 +1484,7 @@ function buildSubPaths(schema) {
495
1484
  }
496
1485
 
497
1486
  // src/openapi/build-spec.ts
498
- var import_utils6 = require("@web-ts-toolkit/utils");
1487
+ var import_utils7 = require("@web-ts-toolkit/utils");
499
1488
 
500
1489
  // src/openapi/responses.ts
501
1490
  var json = (schema) => ({
@@ -566,19 +1555,19 @@ var openApiResponses = {
566
1555
 
567
1556
  // src/openapi/schemas.ts
568
1557
  var import_zod = require("zod");
569
- var import_utils5 = require("@web-ts-toolkit/utils");
1558
+ var import_utils6 = require("@web-ts-toolkit/utils");
570
1559
  var fallbackObjectSchema = { type: "object", additionalProperties: true };
571
1560
  function isOpenApiSchemaPatch(source) {
572
- return (0, import_utils5.isPlainObject)(source) && source.kind === "objectProperties";
1561
+ return (0, import_utils6.isPlainObject)(source) && source.kind === "objectProperties";
573
1562
  }
574
1563
  function isOpenApiSchemaResolver(source) {
575
- return (0, import_utils5.isPlainObject)(source) && source.kind === "schemaResolver" && typeof source.resolve === "function";
1564
+ return (0, import_utils6.isPlainObject)(source) && source.kind === "schemaResolver" && typeof source.resolve === "function";
576
1565
  }
577
1566
  function isJsonSchemaLike(source) {
578
- return (0, import_utils5.isPlainObject)(source) && ("type" in source || "properties" in source || "$ref" in source || "anyOf" in source);
1567
+ return (0, import_utils6.isPlainObject)(source) && ("type" in source || "properties" in source || "$ref" in source || "anyOf" in source);
579
1568
  }
580
1569
  function hasOpenApiSchema(source) {
581
- return (0, import_utils5.isPlainObject)(source) && isJsonSchemaLike(source.openapi);
1570
+ return (0, import_utils6.isPlainObject)(source) && isJsonSchemaLike(source.openapi);
582
1571
  }
583
1572
  function toOpenApiSchema(source) {
584
1573
  if (!source) return void 0;
@@ -586,7 +1575,7 @@ function toOpenApiSchema(source) {
586
1575
  if (!resolvedSource) return void 0;
587
1576
  if (isOpenApiSchemaPatch(resolvedSource)) {
588
1577
  const schema = toOpenApiSchema(resolvedSource.source) ?? { ...fallbackObjectSchema };
589
- const properties = (0, import_utils5.isPlainObject)(schema.properties) ? { ...schema.properties } : {};
1578
+ const properties = (0, import_utils6.isPlainObject)(schema.properties) ? { ...schema.properties } : {};
590
1579
  for (const [key, value] of Object.entries(resolvedSource.properties)) {
591
1580
  properties[key] = toOpenApiSchema(value) ?? fallbackObjectSchema;
592
1581
  }
@@ -619,9 +1608,9 @@ var toOpenApiPath = (path) => normalizePath(path).replace(/:([A-Za-z0-9_]+)/g, "
619
1608
  var schemaToQueryParameters = (schema) => {
620
1609
  const jsonSchema = toOpenApiSchema(schema);
621
1610
  if (!jsonSchema || jsonSchema.type !== "object") return [];
622
- const properties = (0, import_utils6.isPlainObject)(jsonSchema.properties) ? jsonSchema.properties : {};
1611
+ const properties = (0, import_utils7.isPlainObject)(jsonSchema.properties) ? jsonSchema.properties : {};
623
1612
  const required = new Set(
624
- (0, import_utils6.isArray)(jsonSchema.required) ? jsonSchema.required.filter((item) => typeof item === "string") : []
1613
+ (0, import_utils7.isArray)(jsonSchema.required) ? jsonSchema.required.filter((item) => typeof item === "string") : []
625
1614
  );
626
1615
  return Object.entries(properties).map(([name, value]) => ({
627
1616
  name,
@@ -810,12 +1799,12 @@ var OpenApiRegistry = class {
810
1799
  };
811
1800
 
812
1801
  // src/logger-default.ts
813
- var import_node_util = __toESM(require("util"));
1802
+ var import_node_util7 = __toESM(require("util"));
814
1803
  var import_winston = require("winston");
815
1804
  var colorizer = import_winston.format.colorize();
816
1805
  var defaultLogLevel = process.env.WTT_LOG_LEVEL || "silent";
817
1806
  var inspectValue = (value) => {
818
- return typeof value === "string" ? value : import_node_util.default.inspect(value, { depth: 5, colors: false });
1807
+ return typeof value === "string" ? value : import_node_util7.default.inspect(value, { depth: 5, colors: false });
819
1808
  };
820
1809
  var defaultLogger = (0, import_winston.createLogger)({
821
1810
  level: defaultLogLevel,
@@ -836,7 +1825,7 @@ var defaultLogger = (0, import_winston.createLogger)({
836
1825
  });
837
1826
 
838
1827
  // src/options/manager.ts
839
- var import_utils7 = require("@web-ts-toolkit/utils");
1828
+ var import_utils8 = require("@web-ts-toolkit/utils");
840
1829
  var toPath = (key) => {
841
1830
  if (Array.isArray(key)) return key;
842
1831
  return typeof key === "string" ? key.split(".") : [key];
@@ -944,20 +1933,20 @@ var OptionsManager = class {
944
1933
  return this;
945
1934
  }
946
1935
  get(key, defaultValue) {
947
- return (0, import_utils7.get)(this.currentOptions, key, defaultValue);
1936
+ return (0, import_utils8.get)(this.currentOptions, key, defaultValue);
948
1937
  }
949
1938
  set(key, value) {
950
1939
  const path = toPath(key);
951
1940
  if (path.length <= 1) {
952
- (0, import_utils7.set)(this.currentOptions, path, this.preserveKeys.has(String(path[0])) ? value : cloneAndFreezeForStore(value));
1941
+ (0, import_utils8.set)(this.currentOptions, path, this.preserveKeys.has(String(path[0])) ? value : cloneAndFreezeForStore(value));
953
1942
  return;
954
1943
  }
955
1944
  const [rootKey, ...nestedPath] = path;
956
- const currentRoot = (0, import_utils7.get)(this.currentOptions, [rootKey], void 0);
957
- const baseRoot = (0, import_utils7.isPlainObject)(currentRoot) ? currentRoot : {};
1945
+ const currentRoot = (0, import_utils8.get)(this.currentOptions, [rootKey], void 0);
1946
+ const baseRoot = (0, import_utils8.isPlainObject)(currentRoot) ? currentRoot : {};
958
1947
  const nextRoot = cloneConfigValue(baseRoot);
959
- (0, import_utils7.set)(nextRoot, nestedPath, cloneForRead(value));
960
- (0, import_utils7.set)(this.currentOptions, [rootKey], freezeConfigValue(nextRoot));
1948
+ (0, import_utils8.set)(nextRoot, nestedPath, cloneForRead(value));
1949
+ (0, import_utils8.set)(this.currentOptions, [rootKey], freezeConfigValue(nextRoot));
961
1950
  }
962
1951
  fetch() {
963
1952
  const cloned = cloneForRead(this.currentOptions);
@@ -975,10 +1964,10 @@ var OptionsManager = class {
975
1964
  cloned[key] = options[key];
976
1965
  }
977
1966
  }
978
- (0, import_utils7.assign)(this.currentOptions, freezeConfigValue(cloned));
1967
+ (0, import_utils8.assign)(this.currentOptions, freezeConfigValue(cloned));
979
1968
  }
980
1969
  onchange(key, func) {
981
- (0, import_utils7.set)(this.listeners, key, func);
1970
+ (0, import_utils8.set)(this.listeners, key, func);
982
1971
  return this;
983
1972
  }
984
1973
  snapshot() {
@@ -1004,15 +1993,15 @@ var OptionsManager = class {
1004
1993
  cloned[key] = snap[key];
1005
1994
  }
1006
1995
  }
1007
- (0, import_utils7.assign)(current, freezeConfigValue(cloned));
1996
+ (0, import_utils8.assign)(current, freezeConfigValue(cloned));
1008
1997
  }
1009
1998
  };
1010
1999
 
1011
2000
  // src/options/data-manager.ts
1012
- var import_utils8 = require("@web-ts-toolkit/utils");
2001
+ var import_utils9 = require("@web-ts-toolkit/utils");
1013
2002
 
1014
2003
  // src/options/data-values.ts
1015
- var import_node_util2 = require("util");
2004
+ var import_node_util8 = require("util");
1016
2005
  var typedArrays = [
1017
2006
  Int8Array,
1018
2007
  Uint8Array,
@@ -1042,7 +2031,7 @@ var assertNativeProperties = (value, path, allowed = () => false) => {
1042
2031
  }
1043
2032
  };
1044
2033
  var copyBytes = (buffer, path, start = 0, end) => {
1045
- if (!import_node_util2.types.isArrayBuffer(buffer) || Object.getPrototypeOf(buffer) !== ArrayBuffer.prototype) {
2034
+ if (!import_node_util8.types.isArrayBuffer(buffer) || Object.getPrototypeOf(buffer) !== ArrayBuffer.prototype) {
1046
2035
  return unsupported(path, "binary storage must be a fixed, non-shared ArrayBuffer");
1047
2036
  }
1048
2037
  assertNativeProperties(buffer, path);
@@ -1063,7 +2052,7 @@ function copyValue(input, freezePlain, rootPath) {
1063
2052
  return unsupported(path, `${typeof value} values are not supported`);
1064
2053
  }
1065
2054
  if (value === null || typeof value !== "object") return value;
1066
- if (import_node_util2.types.isProxy(value)) return unsupported(path, "proxies are not supported");
2055
+ if (import_node_util8.types.isProxy(value)) return unsupported(path, "proxies are not supported");
1067
2056
  if (active.has(value)) return unsupported(path, "cycles are not supported");
1068
2057
  const previous = copies.get(value);
1069
2058
  if (previous) return previous;
@@ -1084,10 +2073,10 @@ function copyValue(input, freezePlain, rootPath) {
1084
2073
  return freezePlain ? Object.freeze(output2) : output2;
1085
2074
  }
1086
2075
  let output;
1087
- if (prototype === Date.prototype && import_node_util2.types.isDate(value)) {
2076
+ if (prototype === Date.prototype && import_node_util8.types.isDate(value)) {
1088
2077
  assertNativeProperties(value, path);
1089
2078
  output = new Date(Date.prototype.getTime.call(value));
1090
- } else if (prototype === Map.prototype && import_node_util2.types.isMap(value)) {
2079
+ } else if (prototype === Map.prototype && import_node_util8.types.isMap(value)) {
1091
2080
  assertNativeProperties(value, path);
1092
2081
  const map = /* @__PURE__ */ new Map();
1093
2082
  copies.set(value, map);
@@ -1097,7 +2086,7 @@ function copyValue(input, freezePlain, rootPath) {
1097
2086
  index += 1;
1098
2087
  }
1099
2088
  output = map;
1100
- } else if (prototype === Set.prototype && import_node_util2.types.isSet(value)) {
2089
+ } else if (prototype === Set.prototype && import_node_util8.types.isSet(value)) {
1101
2090
  assertNativeProperties(value, path);
1102
2091
  const set4 = /* @__PURE__ */ new Set();
1103
2092
  copies.set(value, set4);
@@ -1107,7 +2096,7 @@ function copyValue(input, freezePlain, rootPath) {
1107
2096
  index += 1;
1108
2097
  }
1109
2098
  output = set4;
1110
- } else if (prototype === RegExp.prototype && import_node_util2.types.isRegExp(value)) {
2099
+ } else if (prototype === RegExp.prototype && import_node_util8.types.isRegExp(value)) {
1111
2100
  assertNativeProperties(value, path, (key) => key === "lastIndex");
1112
2101
  const regexp = value;
1113
2102
  if (typeof regexp.lastIndex !== "number") return unsupported(path, "RegExp.lastIndex must be a number");
@@ -1184,7 +2173,7 @@ var emptyDataSnapshot = Object.freeze([]);
1184
2173
  var ownedSnapshots = new WeakMap([[emptyDataSnapshot, emptyDataSnapshot]]);
1185
2174
  function createDataSnapshot(data) {
1186
2175
  if (data === void 0) return void 0;
1187
- if (!Array.isArray(data) || import_node_util2.types.isProxy(data) || Object.getPrototypeOf(data) !== Array.prototype) {
2176
+ if (!Array.isArray(data) || import_node_util8.types.isProxy(data) || Object.getPrototypeOf(data) !== Array.prototype) {
1188
2177
  return unsupported("data", "expected an ordinary array or undefined");
1189
2178
  }
1190
2179
  if (ownedSnapshots.has(data)) return data;
@@ -1215,19 +2204,159 @@ var DataOptionsManager = class extends OptionsManager {
1215
2204
  super.set("data", createDataSnapshot(value));
1216
2205
  } else if (path.startsWith("data.")) {
1217
2206
  const next = copyDataValue(getOwnedDataSnapshot(super.get("data")));
1218
- (0, import_utils8.set)(next, path.slice("data.".length), value);
2207
+ (0, import_utils9.set)(next, path.slice("data.".length), value);
1219
2208
  super.set("data", createDataSnapshot(next));
1220
2209
  } else {
1221
2210
  super.set(key, value);
1222
2211
  }
1223
2212
  }
1224
- restore(snapshot) {
1225
- super.restore(admitData(snapshot));
1226
- }
1227
- };
2213
+ restore(snapshot) {
2214
+ super.restore(admitData(snapshot));
2215
+ }
2216
+ };
2217
+
2218
+ // src/operation-access.ts
2219
+ var operations = /* @__PURE__ */ new Set(["new", "list", "read", "create", "update", "upsert", "delete", "count", "distinct"]);
2220
+ var subOperations = /* @__PURE__ */ new Set(["list", "read", "create", "update", "delete"]);
2221
+ var members = /* @__PURE__ */ new Set(["default", "basic", "advanced", "root"]);
2222
+ var removedAccesses = new Set(
2223
+ ["List", "Read", "Create", "Update", "Upsert", "Count", "Distinct"].flatMap((operation) => [
2224
+ `basic${operation}`,
2225
+ `advanced${operation}`
2226
+ ])
2227
+ );
2228
+ var isRemovedOperationAccess = (access) => typeof access === "string" && removedAccesses.has(access);
2229
+ function isOperationAccessMemberPath(access) {
2230
+ const keys2 = access.split(".");
2231
+ if (operations.has(keys2[0]) && members.has(keys2[1])) return true;
2232
+ return keys2[0] === "subs" && keys2[1] !== "" && subOperations.has(keys2[2]) && members.has(keys2[3]);
2233
+ }
2234
+ var isRecord = (value) => value !== null && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
2235
+ function readOwnOption(root, key) {
2236
+ let value = root;
2237
+ for (const part of key.split(".")) {
2238
+ if (value === null || typeof value !== "object") return void 0;
2239
+ const slot = Object.getOwnPropertyDescriptor(value, part);
2240
+ if (!slot || !("value" in slot)) return void 0;
2241
+ value = slot.value;
2242
+ }
2243
+ return value;
2244
+ }
2245
+ function createOperationAccessReaders(options, defaults2) {
2246
+ return {
2247
+ readOption: (key) => readOwnOption(options, key),
2248
+ readDefaultOption: defaults2 === void 0 ? void 0 : (key) => readOwnOption(defaults2, key)
2249
+ };
2250
+ }
2251
+ var scalarGuard = (value) => {
2252
+ if (value === void 0) return void 0;
2253
+ if (typeof value === "boolean" || typeof value === "string" || typeof value === "function")
2254
+ return value;
2255
+ if (Array.isArray(value) && value.every((entry) => typeof entry === "string")) return value;
2256
+ return false;
2257
+ };
2258
+ function operationDefault(value) {
2259
+ if (!isRecord(value)) return scalarGuard(value);
2260
+ if (Reflect.ownKeys(value).some((key) => typeof key !== "string" || !members.has(key))) return false;
2261
+ return scalarGuard(readOwnOption(value, "default"));
2262
+ }
2263
+ function selectOperationAccessGuard({
2264
+ baseAccess,
2265
+ context,
2266
+ readOption,
2267
+ readDefaultOption,
2268
+ subdocuments = false
2269
+ }) {
2270
+ const keys2 = baseAccess.split(".");
2271
+ if (isRemovedOperationAccess(baseAccess) || isOperationAccessMemberPath(baseAccess) || keys2[0] === "subs" && isRemovedOperationAccess(keys2[2]))
2272
+ return false;
2273
+ if (context !== void 0 && !["basic", "advanced", "root"].includes(context)) return false;
2274
+ const exact = (key) => {
2275
+ const value = readOption(key);
2276
+ return value === void 0 ? readDefaultOption?.(key) : value;
2277
+ };
2278
+ const contextGuard = (key, supported) => context === void 0 || !supported ? void 0 : scalarGuard(exact(`${key}.${context}`));
2279
+ let access = baseAccess;
2280
+ if (subdocuments && keys2[0] === "subs") {
2281
+ if (keys2.length < 3 || keys2[1] === "") return false;
2282
+ const fieldKey = `operationAccess.subs.${keys2[1]}`;
2283
+ const operationKey2 = `operationAccess.${baseAccess}`;
2284
+ const selected2 = contextGuard(operationKey2, keys2.length === 3 && subOperations.has(keys2[2]));
2285
+ if (selected2 !== void 0) return selected2;
2286
+ const operation2 = exact(operationKey2);
2287
+ if (operation2 !== void 0) {
2288
+ const guard = keys2.length === 3 && subOperations.has(keys2[2]) ? operationDefault(operation2) : scalarGuard(operation2);
2289
+ if (guard !== void 0) return guard;
2290
+ }
2291
+ const field = exact(fieldKey);
2292
+ if (field !== void 0) return scalarGuard(field);
2293
+ access = keys2[2];
2294
+ }
2295
+ const operationKey = `operationAccess.${access}`;
2296
+ const selected = contextGuard(operationKey, operations.has(access));
2297
+ if (selected !== void 0) return selected;
2298
+ const operation = readOption(operationKey);
2299
+ if (operation !== void 0) {
2300
+ const guard = operations.has(access) ? operationDefault(operation) : scalarGuard(operation);
2301
+ if (guard !== void 0) return guard;
2302
+ }
2303
+ const outerDefault = readOption("operationAccess.default");
2304
+ if (outerDefault !== void 0) return scalarGuard(outerDefault);
2305
+ const outer = readOption("operationAccess");
2306
+ if (outer !== void 0) return scalarGuard(outer);
2307
+ const inherited = readDefaultOption?.(operationKey);
2308
+ return operations.has(access) ? operationDefault(inherited) : scalarGuard(inherited);
2309
+ }
2310
+ function rejectRemovedKey(key, prefix) {
2311
+ const context = key.startsWith("basic") ? "basic" : "advanced";
2312
+ const operation = key.slice(context.length);
2313
+ const replacement = `${operation[0].toLowerCase()}${operation.slice(1)}.${context}`;
2314
+ throw new TypeError(
2315
+ `Removed operation-access key "${prefix}${key}"; use "${prefix}${replacement}" instead. Move the operation's former scalar guard to its "default" member when using an object.`
2316
+ );
2317
+ }
2318
+ function assertOperationNode(node, prefix) {
2319
+ if (!node || typeof node !== "object" || Array.isArray(node)) return;
2320
+ for (const key of removedAccesses) if (key in node) rejectRemovedKey(key, prefix);
2321
+ for (const key of Object.getOwnPropertyNames(node)) {
2322
+ const [operation] = key.split(".");
2323
+ if (isRemovedOperationAccess(operation)) rejectRemovedKey(operation, prefix);
2324
+ }
2325
+ }
2326
+ function assertOperationAccessOptions(options) {
2327
+ if (!options || typeof options !== "object") return;
2328
+ for (const key of Object.getOwnPropertyNames(options)) {
2329
+ if (key === "operationAccess" || key.startsWith("operationAccess.")) {
2330
+ assertOperationAccessUpdate(key, options[key]);
2331
+ }
2332
+ }
2333
+ }
2334
+ function assertOperationAccessUpdate(key, value) {
2335
+ const path = key.split(".");
2336
+ if (path[0] !== "operationAccess") return;
2337
+ if (isRemovedOperationAccess(path[1])) rejectRemovedKey(path[1], "operationAccess.");
2338
+ if (path[1] === "subs" && path.length >= 4 && isRemovedOperationAccess(path[3]))
2339
+ rejectRemovedKey(path[3], `operationAccess.subs.${path[2]}.`);
2340
+ if (path.length === 1) {
2341
+ assertOperationNode(value, "operationAccess.");
2342
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2343
+ for (const property of Object.getOwnPropertyNames(value)) {
2344
+ if (property === "subs" || property.startsWith("subs."))
2345
+ assertOperationAccessUpdate(`operationAccess.${property}`, value[property]);
2346
+ }
2347
+ }
2348
+ } else if (path.length === 2 && path[1] === "subs") {
2349
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2350
+ for (const field of Object.getOwnPropertyNames(value))
2351
+ assertOperationAccessUpdate(`operationAccess.subs.${field}`, value[field]);
2352
+ }
2353
+ } else if (path.length === 3 && path[1] === "subs") {
2354
+ assertOperationNode(value, `${key}.`);
2355
+ }
2356
+ }
1228
2357
 
1229
2358
  // src/request-complexity.ts
1230
- var import_utils9 = require("@web-ts-toolkit/utils");
2359
+ var import_utils10 = require("@web-ts-toolkit/utils");
1231
2360
  var defaultRequestComplexity = {
1232
2361
  maxDepth: 8,
1233
2362
  maxNodes: 500,
@@ -1250,364 +2379,148 @@ var resolveRequestComplexity = (options) => ({
1250
2379
  maxLogicalClauses: normalizePositiveInteger(options?.maxLogicalClauses, defaultRequestComplexity.maxLogicalClauses),
1251
2380
  maxInValues: normalizePositiveInteger(options?.maxInValues, defaultRequestComplexity.maxInValues),
1252
2381
  maxBulkItems: normalizePositiveInteger(options?.maxBulkItems, defaultRequestComplexity.maxBulkItems),
1253
- maxIncludeCount: normalizePositiveInteger(options?.maxIncludeCount, defaultRequestComplexity.maxIncludeCount),
1254
- maxSubQueryCount: normalizePositiveInteger(options?.maxSubQueryCount, defaultRequestComplexity.maxSubQueryCount),
1255
- maxBulkConcurrency: normalizePositiveInteger(
1256
- options?.maxBulkConcurrency,
1257
- defaultRequestComplexity.maxBulkConcurrency
1258
- ),
1259
- maxHookConcurrency: normalizePositiveInteger(
1260
- options?.maxHookConcurrency,
1261
- defaultRequestComplexity.maxHookConcurrency
1262
- ),
1263
- maxCorrelatedQueries: normalizePositiveInteger(
1264
- options?.maxCorrelatedQueries,
1265
- defaultRequestComplexity.maxCorrelatedQueries
1266
- ),
1267
- maxCorrelatedDepth: normalizePositiveInteger(
1268
- options?.maxCorrelatedDepth,
1269
- defaultRequestComplexity.maxCorrelatedDepth
1270
- )
1271
- });
1272
- function validateRequestComplexity(value, options, scope = "request") {
1273
- const limits = resolveRequestComplexity(options);
1274
- const errors = [];
1275
- let nodes = 0;
1276
- let logicalClauses = 0;
1277
- let includeCount = 0;
1278
- let subQueryCount = 0;
1279
- const pointer = (path) => path.length === 0 ? "#" : `#/${path.join("/")}`;
1280
- const pushError = (detail, path) => {
1281
- if (errors.length === 0) {
1282
- errors.push({ detail, pointer: pointer(path) });
1283
- }
1284
- };
1285
- const visit = (current, path, depth, parentKey) => {
1286
- if (errors.length > 0) return;
1287
- nodes += 1;
1288
- if (nodes > limits.maxNodes) {
1289
- pushError(`Request exceeds maximum node budget of ${limits.maxNodes}`, path);
1290
- return;
1291
- }
1292
- if (depth > limits.maxDepth) {
1293
- pushError(`Request exceeds maximum depth of ${limits.maxDepth}`, path);
1294
- return;
1295
- }
1296
- if ((0, import_utils9.isArray)(current)) {
1297
- if (parentKey === "$and" || parentKey === "$or" || parentKey === "$nor") {
1298
- logicalClauses += current.length;
1299
- if (logicalClauses > limits.maxLogicalClauses) {
1300
- pushError(`Filter exceeds maximum logical clause budget of ${limits.maxLogicalClauses}`, path);
1301
- return;
1302
- }
1303
- }
1304
- if (parentKey === "$in") {
1305
- if (current.length > limits.maxInValues) {
1306
- pushError(`Filter exceeds maximum $in values of ${limits.maxInValues}`, path);
1307
- return;
1308
- }
1309
- }
1310
- for (let index = 0; index < current.length; index++) {
1311
- visit(current[index], path.concat(index), depth + 1, parentKey);
1312
- if (errors.length > 0) return;
1313
- }
1314
- return;
1315
- }
1316
- if (!(0, import_utils9.isPlainObject)(current)) return;
1317
- for (const [key, child] of Object.entries(current)) {
1318
- if (key === "__proto__" || key === "prototype" || key === "constructor") {
1319
- pushError(`Unsupported key: ${key}`, path.concat(key));
1320
- return;
1321
- }
1322
- if (scope === "request" && key === "include") {
1323
- includeCount += (0, import_utils9.isArray)(child) ? child.length : 1;
1324
- if (includeCount > limits.maxIncludeCount) {
1325
- pushError(`Request exceeds maximum include count of ${limits.maxIncludeCount}`, path.concat(key));
1326
- return;
1327
- }
1328
- }
1329
- if (key === "$$sq") {
1330
- subQueryCount += 1;
1331
- if (subQueryCount > limits.maxSubQueryCount) {
1332
- pushError(`Request exceeds maximum subquery count of ${limits.maxSubQueryCount}`, path.concat(key));
1333
- return;
1334
- }
1335
- visit(child, path.concat(key), depth + 1, key);
1336
- if (errors.length > 0) return;
1337
- continue;
1338
- }
1339
- visit(child, path.concat(key), depth + 1, key);
1340
- if (errors.length > 0) return;
1341
- }
1342
- };
1343
- visit(value, [], 0);
1344
- return errors;
1345
- }
1346
-
1347
- // src/acl/virtual-descriptor.ts
1348
- var import_utils10 = require("@web-ts-toolkit/utils");
1349
- var isVirtualContainerValue = (value) => (0, import_utils10.isPlainObject)(value) && "sub" in value;
1350
- function getScopeVirtualsObject(root, scopePath = []) {
1351
- let current = root;
1352
- for (let i = 0; i < scopePath.length; i += 2) {
1353
- if (!current || scopePath[i + 1] !== "sub") return null;
1354
- const container = current[scopePath[i]];
1355
- if (!isVirtualContainerValue(container)) return null;
1356
- current = container.sub;
1357
- }
1358
- return (0, import_utils10.isPlainObject)(current) ? current : null;
1359
- }
1360
- function toDescriptor(leaf, shared = {}) {
1361
- const record2 = (0, import_utils10.isFunction)(leaf) ? { get: leaf } : (0, import_utils10.isPlainObject)(leaf) ? leaf : null;
1362
- if (!record2 || !(0, import_utils10.isFunction)(record2.get)) return void 0;
1363
- const dependsOn = record2.dependsOn ?? shared.dependsOn ?? [];
1364
- const populated = record2.dependsOnPopulate === void 0 ? shared.dependsOnPopulate : record2.dependsOnPopulate;
1365
- return {
1366
- get: record2.get,
1367
- dependsOn: [...dependsOn],
1368
- ...populated === void 0 ? {} : {
1369
- dependsOnPopulate: populated.map(({ path, select }) => ({
1370
- path,
1371
- ...select === void 0 ? {} : { select: Array.isArray(select) ? [...select] : typeof select === "object" ? { ...select } : select }
1372
- }))
1373
- }
1374
- };
1375
- }
1376
- function resolveSnapshotDescriptor(scopeVirtuals, virtualName, access) {
1377
- const entry = scopeVirtuals?.[virtualName];
1378
- if (entry === void 0 || isVirtualContainerValue(entry)) return void 0;
1379
- if ((0, import_utils10.isFunction)(entry)) return toDescriptor(entry);
1380
- if (!(0, import_utils10.isPlainObject)(entry)) return void 0;
1381
- const record2 = entry;
1382
- if ("get" in record2) return toDescriptor(record2);
1383
- return toDescriptor(record2[access], record2) ?? toDescriptor(record2.default, record2);
1384
- }
1385
-
1386
- // src/acl/virtual-populate-dependencies.ts
1387
- var import_utils12 = require("@web-ts-toolkit/utils");
1388
-
1389
- // src/acl/authorization-snapshot.ts
1390
- var import_node_util3 = require("util");
1391
- var import_node_buffer = require("buffer");
1392
- var import_mongoose2 = require("mongoose");
1393
- var import_express_json_router2 = __toESM(require("@web-ts-toolkit/express-json-router"));
1394
- var ServiceAuthorizationError = class extends import_express_json_router2.default.clientErrors.BadRequestError {
1395
- constructor(detail) {
1396
- const errors = [{ detail: `Service authorization: ${detail}` }];
1397
- super("Bad Request", { errors });
1398
- this.result = { success: false, kind: "error", code: "bad_request" /* BadRequest */, errors };
1399
- }
1400
- };
1401
- function authorizationError(detail) {
1402
- throw new ServiceAuthorizationError(detail);
1403
- }
1404
- var unsafeKeys = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1405
- function authorizationRecord(value, label) {
1406
- if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
1407
- authorizationError(`${label} must be a plain object`);
1408
- }
1409
- return value;
1410
- }
1411
- function copyAuthorizationValue(value, configuration = false) {
1412
- const active = /* @__PURE__ */ new WeakSet();
1413
- let nodes = 0;
1414
- function copy(input, depth) {
1415
- if (++nodes > 2e4 || depth > 100) authorizationError("snapshot exceeds structural limits");
1416
- if (typeof input === "function") {
1417
- if (configuration === true) return input;
1418
- authorizationError("functions are not policy values");
1419
- }
1420
- if (typeof input === "symbol") authorizationError("symbols are not policy values");
1421
- if (input === null || typeof input !== "object") return input;
1422
- if (active.has(input)) authorizationError("cyclic input");
1423
- active.add(input);
1424
- try {
1425
- if (input instanceof Date) return new Date(input.getTime());
1426
- if (Buffer.isBuffer(input)) return Buffer.from(input);
1427
- if (input instanceof RegExp) {
1428
- const result2 = new RegExp(input.source, input.flags);
1429
- result2.lastIndex = input.lastIndex;
1430
- return result2;
1431
- }
1432
- if (input instanceof import_mongoose2.mongo.BSON.BSONValue) {
1433
- try {
1434
- return import_mongoose2.mongo.BSON.deserialize(import_mongoose2.mongo.BSON.serialize({ value: input }), {
1435
- promoteValues: false,
1436
- bsonRegExp: true
1437
- }).value;
1438
- } catch {
1439
- authorizationError("unsupported BSON snapshot");
1440
- }
1441
- }
1442
- if (configuration && input instanceof Map) {
1443
- return new Map([...input].map(([key, entry]) => [copy(key, depth + 1), copy(entry, depth + 1)]));
1444
- }
1445
- if (configuration && input instanceof Set) return new Set([...input].map((entry) => copy(entry, depth + 1)));
1446
- const array = Array.isArray(input);
1447
- if (array && input.length > 2e4) authorizationError("snapshot array exceeds structural limits");
1448
- if (!array) authorizationRecord(input, "snapshot");
1449
- const result = array ? [] : {};
1450
- let definedProperty = false;
1451
- for (const key of Reflect.ownKeys(input)) {
1452
- if (array && key === "length") continue;
1453
- if (typeof key !== "string" || unsafeKeys.has(key)) authorizationError("unsafe snapshot key");
1454
- if (array && !/^(0|[1-9]\d*)$/.test(key)) authorizationError("invalid array property");
1455
- const descriptor = Object.getOwnPropertyDescriptor(input, key);
1456
- if (!("value" in descriptor) || !descriptor.enumerable && configuration !== "document")
1457
- authorizationError("accessor/non-enumerable input");
1458
- const value2 = copy(descriptor.value, depth + 1);
1459
- if (array || definedProperty && Object.getPrototypeOf(result) !== Object.prototype || key in result) {
1460
- definedProperty = true;
1461
- Object.defineProperty(result, key, {
1462
- value: value2,
1463
- enumerable: true,
1464
- writable: true,
1465
- configurable: true
1466
- });
1467
- } else result[key] = value2;
1468
- }
1469
- if (array) result.length = input.length;
1470
- return Object.freeze(result);
1471
- } finally {
1472
- active.delete(input);
1473
- }
1474
- }
1475
- return copy(value, 0);
1476
- }
1477
-
1478
- // src/acl/field-catalog.ts
1479
- var import_node_util4 = require("util");
1480
- 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);
1481
- var isSafeOutputPath = (path) => path.split(".").every(safeSegment);
1482
- var inputControlSegments = /* @__PURE__ */ new Set([
1483
- "_permissions",
1484
- "_view",
1485
- "_edit",
1486
- "documentAuthorization",
1487
- "documentAuthorizationStage",
1488
- "resolvedAuthorization",
1489
- "execution",
1490
- "executionContext",
1491
- "serviceExecutionContext",
1492
- "preparedQuery",
1493
- "preparedFilter",
1494
- "preparedModelQuery",
1495
- "resolvedIdentifier",
1496
- "skipParsing",
1497
- "skipAuthorization",
1498
- "alreadyAuthorized"
1499
- ]);
1500
- function isSafeInputPath(path, requestIdentity = false) {
1501
- return isSafeOutputPath(path) && path.split(".").every((part) => !inputControlSegments.has(part) && (requestIdentity || part !== "_id"));
1502
- }
1503
- function matchesCatalogPattern(pattern, path, descendants = false) {
1504
- if (typeof pattern === "string" && typeof path === "string" && !pattern.includes("$*")) {
1505
- return pattern === path || !!descendants && path.startsWith(pattern) && path[pattern.length] === ".";
1506
- }
1507
- const expected = pattern.split(".");
1508
- const actual = path.split(".");
1509
- return (descendants ? actual.length >= expected.length : actual.length === expected.length) && expected.every((part, index) => part === "$*" || part === actual[index]);
1510
- }
1511
- function captureAuthorizationFieldCatalog(schema, virtuals, documentPermissionField = "_permissions") {
1512
- const paths = /* @__PURE__ */ new Set();
1513
- const containers = /* @__PURE__ */ new Set();
1514
- const opaque = /* @__PURE__ */ new Set();
1515
- const references = /* @__PURE__ */ new Set();
1516
- const virtualPaths = /* @__PURE__ */ new Set();
1517
- const virtualScopes = /* @__PURE__ */ new Set();
1518
- const schemaVirtualPaths = /* @__PURE__ */ new Set();
1519
- const arrays = /* @__PURE__ */ new Set();
1520
- const protectedPaths = /* @__PURE__ */ new Set([documentPermissionField, "_doc", "$__", "__v"]);
1521
- const add = (path) => {
1522
- if (path.split(".").every((part) => part === "$*" || safeSegment(part))) paths.add(path);
1523
- };
1524
- const ancestors = (path) => {
1525
- const parts = path.split(".");
1526
- for (let n = 1; n < parts.length; n++) {
1527
- const parent = parts.slice(0, n).join(".");
1528
- add(parent);
1529
- containers.add(parent);
2382
+ maxIncludeCount: normalizePositiveInteger(options?.maxIncludeCount, defaultRequestComplexity.maxIncludeCount),
2383
+ maxSubQueryCount: normalizePositiveInteger(options?.maxSubQueryCount, defaultRequestComplexity.maxSubQueryCount),
2384
+ maxBulkConcurrency: normalizePositiveInteger(
2385
+ options?.maxBulkConcurrency,
2386
+ defaultRequestComplexity.maxBulkConcurrency
2387
+ ),
2388
+ maxHookConcurrency: normalizePositiveInteger(
2389
+ options?.maxHookConcurrency,
2390
+ defaultRequestComplexity.maxHookConcurrency
2391
+ ),
2392
+ maxCorrelatedQueries: normalizePositiveInteger(
2393
+ options?.maxCorrelatedQueries,
2394
+ defaultRequestComplexity.maxCorrelatedQueries
2395
+ ),
2396
+ maxCorrelatedDepth: normalizePositiveInteger(
2397
+ options?.maxCorrelatedDepth,
2398
+ defaultRequestComplexity.maxCorrelatedDepth
2399
+ )
2400
+ });
2401
+ function validateRequestComplexity(value, options, scope = "request") {
2402
+ const limits = resolveRequestComplexity(options);
2403
+ const errors = [];
2404
+ let nodes = 0;
2405
+ let logicalClauses = 0;
2406
+ let includeCount = 0;
2407
+ let subQueryCount = 0;
2408
+ const pointer = (path) => path.length === 0 ? "#" : `#/${path.join("/")}`;
2409
+ const pushError = (detail, path) => {
2410
+ if (errors.length === 0) {
2411
+ errors.push({ detail, pointer: pointer(path) });
1530
2412
  }
1531
2413
  };
1532
- const visitType = (type, path, active) => {
1533
- add(path);
1534
- ancestors(path);
1535
- const element = type.$embeddedSchemaType ?? type.embeddedSchemaType ?? type.caster;
1536
- if (type.instance === "Array" || type.$isMongooseDocumentArray) arrays.add(path);
1537
- if (type.options?.ref || type.options?.refPath || element?.options?.ref || element?.options?.refPath) {
1538
- references.add(path);
2414
+ const visit = (current, path, depth, parentKey) => {
2415
+ if (errors.length > 0) return;
2416
+ nodes += 1;
2417
+ if (nodes > limits.maxNodes) {
2418
+ pushError(`Request exceeds maximum node budget of ${limits.maxNodes}`, path);
1539
2419
  return;
1540
2420
  }
1541
- if (type.$isSchemaMap || type.instance === "Map") {
1542
- const value = type.$__schemaType;
1543
- if (value) visitType(value, `${path}.$*`, active);
1544
- else opaque.add(path);
1545
- containers.delete(path);
2421
+ if (depth > limits.maxDepth) {
2422
+ pushError(`Request exceeds maximum depth of ${limits.maxDepth}`, path);
1546
2423
  return;
1547
2424
  }
1548
- const child = type.schema ?? element?.schema;
1549
- if (child) {
1550
- containers.add(path);
1551
- if (!active.has(child)) visitSchema(child, path, /* @__PURE__ */ new Set([...active, child]));
2425
+ if ((0, import_utils10.isArray)(current)) {
2426
+ if (parentKey === "$and" || parentKey === "$or" || parentKey === "$nor") {
2427
+ logicalClauses += current.length;
2428
+ if (logicalClauses > limits.maxLogicalClauses) {
2429
+ pushError(`Filter exceeds maximum logical clause budget of ${limits.maxLogicalClauses}`, path);
2430
+ return;
2431
+ }
2432
+ }
2433
+ if (parentKey === "$in") {
2434
+ if (current.length > limits.maxInValues) {
2435
+ pushError(`Filter exceeds maximum $in values of ${limits.maxInValues}`, path);
2436
+ return;
2437
+ }
2438
+ }
2439
+ for (let index = 0; index < current.length; index++) {
2440
+ visit(current[index], path.concat(index), depth + 1, parentKey);
2441
+ if (errors.length > 0) return;
2442
+ }
1552
2443
  return;
1553
2444
  }
1554
- if (type.instance === "Mixed" || element?.instance === "Mixed") opaque.add(path);
1555
- };
1556
- const visitSchema = (current, prefix, active) => {
1557
- const version = current.options.versionKey;
1558
- if (typeof version === "string") protectedPaths.add(prefix ? `${prefix}.${version}` : version);
1559
- for (const name of Object.keys(current.virtuals)) {
1560
- schemaVirtualPaths.add(prefix ? `${prefix}.${name}` : name);
1561
- }
1562
- for (const [name, raw] of Object.entries(current.paths)) {
1563
- if (name.includes("$*")) continue;
1564
- visitType(raw, prefix ? `${prefix}.${name}` : name, active);
2445
+ if (!(0, import_utils10.isPlainObject)(current)) return;
2446
+ for (const [key, child] of Object.entries(current)) {
2447
+ if (key === "__proto__" || key === "prototype" || key === "constructor") {
2448
+ pushError(`Unsupported key: ${key}`, path.concat(key));
2449
+ return;
2450
+ }
2451
+ if (scope === "request" && key === "include") {
2452
+ includeCount += (0, import_utils10.isArray)(child) ? child.length : 1;
2453
+ if (includeCount > limits.maxIncludeCount) {
2454
+ pushError(`Request exceeds maximum include count of ${limits.maxIncludeCount}`, path.concat(key));
2455
+ return;
2456
+ }
2457
+ }
2458
+ if (key === "$$sq") {
2459
+ subQueryCount += 1;
2460
+ if (subQueryCount > limits.maxSubQueryCount) {
2461
+ pushError(`Request exceeds maximum subquery count of ${limits.maxSubQueryCount}`, path.concat(key));
2462
+ return;
2463
+ }
2464
+ visit(child, path.concat(key), depth + 1, key);
2465
+ if (errors.length > 0) return;
2466
+ continue;
2467
+ }
2468
+ visit(child, path.concat(key), depth + 1, key);
2469
+ if (errors.length > 0) return;
1565
2470
  }
1566
2471
  };
1567
- visitSchema(schema, "", /* @__PURE__ */ new Set([schema]));
1568
- const persistedPaths = [...paths];
1569
- const visitVirtuals = (record2, prefix) => {
1570
- for (const [name, value] of Object.entries(record2 ?? {})) {
1571
- if (value === void 0) continue;
1572
- const path = prefix ? `${prefix}.${name}` : name;
1573
- if (!isSafeOutputPath(path)) continue;
1574
- if (value && typeof value === "object" && "sub" in value) {
1575
- if (references.has(path)) continue;
1576
- virtualScopes.add(path);
1577
- add(path);
1578
- containers.add(path);
1579
- visitVirtuals(value.sub, path);
1580
- } else {
1581
- add(path);
1582
- ancestors(path);
1583
- virtualPaths.add(path);
1584
- }
2472
+ visit(value, [], 0);
2473
+ return errors;
2474
+ }
2475
+
2476
+ // src/acl/virtual-descriptor.ts
2477
+ var import_utils11 = require("@web-ts-toolkit/utils");
2478
+ var isVirtualContainerValue = (value) => (0, import_utils11.isPlainObject)(value) && "sub" in value;
2479
+ function getScopeVirtualsObject(root, scopePath = []) {
2480
+ let current = root;
2481
+ for (let i = 0; i < scopePath.length; i += 2) {
2482
+ if (!current || scopePath[i + 1] !== "sub") return null;
2483
+ const container = current[scopePath[i]];
2484
+ if (!isVirtualContainerValue(container)) return null;
2485
+ current = container.sub;
2486
+ }
2487
+ return (0, import_utils11.isPlainObject)(current) ? current : null;
2488
+ }
2489
+ function toDescriptor(leaf, shared = {}) {
2490
+ const record2 = (0, import_utils11.isFunction)(leaf) ? { get: leaf } : (0, import_utils11.isPlainObject)(leaf) ? leaf : null;
2491
+ if (!record2 || !(0, import_utils11.isFunction)(record2.get)) return void 0;
2492
+ const dependsOn = record2.dependsOn ?? shared.dependsOn ?? [];
2493
+ const populated = record2.dependsOnPopulate === void 0 ? shared.dependsOnPopulate : record2.dependsOnPopulate;
2494
+ return {
2495
+ get: record2.get,
2496
+ dependsOn: [...dependsOn],
2497
+ ...populated === void 0 ? {} : {
2498
+ dependsOnPopulate: populated.map(({ path, select }) => ({
2499
+ path,
2500
+ ...select === void 0 ? {} : { select: Array.isArray(select) ? [...select] : typeof select === "object" ? { ...select } : select }
2501
+ }))
1585
2502
  }
1586
2503
  };
1587
- visitVirtuals(virtuals, "");
1588
- const eligible = [...paths].filter((p) => ![...protectedPaths].some((v) => matchesCatalogPattern(v, p, true)));
1589
- return Object.freeze({
1590
- paths: Object.freeze(eligible.filter((p) => !p.includes("$*"))),
1591
- persistedPaths: Object.freeze(persistedPaths),
1592
- arrayPaths: Object.freeze([...arrays]),
1593
- schemaVirtualPaths: Object.freeze([...schemaVirtualPaths]),
1594
- metadataPaths: Object.freeze([documentPermissionField]),
1595
- dynamicPaths: Object.freeze(eligible.filter((p) => p.includes("$*"))),
1596
- containerPaths: Object.freeze([...containers]),
1597
- opaquePaths: Object.freeze([...opaque]),
1598
- referencePaths: Object.freeze([...references]),
1599
- virtualPaths: Object.freeze([...virtualPaths]),
1600
- virtualScopePaths: Object.freeze([...virtualScopes]),
1601
- protectedPaths: Object.freeze([...protectedPaths])
1602
- });
1603
2504
  }
2505
+ function resolveSnapshotDescriptor(scopeVirtuals, virtualName, access) {
2506
+ const entry = scopeVirtuals?.[virtualName];
2507
+ if (entry === void 0 || isVirtualContainerValue(entry)) return void 0;
2508
+ if ((0, import_utils11.isFunction)(entry)) return toDescriptor(entry);
2509
+ if (!(0, import_utils11.isPlainObject)(entry)) return void 0;
2510
+ const record2 = entry;
2511
+ if ("get" in record2) return toDescriptor(record2);
2512
+ return toDescriptor(record2[access], record2) ?? toDescriptor(record2.default, record2);
2513
+ }
2514
+
2515
+ // src/acl/virtual-populate-dependencies.ts
2516
+ var import_utils13 = require("@web-ts-toolkit/utils");
1604
2517
 
1605
2518
  // src/acl/populate-target-configuration.ts
1606
- var import_utils11 = require("@web-ts-toolkit/utils");
2519
+ var import_utils12 = require("@web-ts-toolkit/utils");
1607
2520
 
1608
2521
  // src/runtime-context.ts
1609
- var import_node_async_hooks = require("async_hooks");
1610
- var runtimeStorage = new import_node_async_hooks.AsyncLocalStorage();
2522
+ var import_node_async_hooks2 = require("async_hooks");
2523
+ var runtimeStorage = new import_node_async_hooks2.AsyncLocalStorage();
1611
2524
  function getActiveRuntime() {
1612
2525
  return runtimeStorage.getStore() ?? null;
1613
2526
  }
@@ -1623,7 +2536,7 @@ function capturePopulateTargetConfiguration(runtime, modelName, source, proposed
1623
2536
  if (!model) authorizationError(`${label} requires an actual registered Mongoose model in this runtime`);
1624
2537
  const options = proposedOptions ?? runtime.getModelOptions(modelName);
1625
2538
  const permissionSchema = options.permissionSchema === void 0 ? defaults2.permissionSchema : options.permissionSchema;
1626
- if (!(0, import_utils11.isPlainObject)(permissionSchema))
2539
+ if (!(0, import_utils12.isPlainObject)(permissionSchema))
1627
2540
  authorizationError(
1628
2541
  `${label} requires an effective object permissionSchema; configure the model or runtime model defaults ({} explicitly closes business fields)`
1629
2542
  );
@@ -1666,7 +2579,7 @@ var fail = (label, message) => {
1666
2579
  var varyingSchema = (schema) => Object.keys(schema.discriminators ?? {}).length > 0 || schema.discriminatorMapping?.isRoot === false;
1667
2580
  var varyingModel = (model) => !!model.baseModelName || Object.keys(model.discriminators ?? {}).length > 0 || varyingSchema(model.schema);
1668
2581
  function record(value, label) {
1669
- if (!(0, import_utils12.isPlainObject)(value)) return fail(label, "entries must be plain { path, select? } objects");
2582
+ if (!(0, import_utils13.isPlainObject)(value)) return fail(label, "entries must be plain { path, select? } objects");
1670
2583
  for (const key of Reflect.ownKeys(value)) {
1671
2584
  const property = Object.getOwnPropertyDescriptor(value, key);
1672
2585
  if (typeof key !== "string" || !property.enumerable || !("value" in property))
@@ -1802,7 +2715,7 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, populat
1802
2715
  proposed?.defaults
1803
2716
  );
1804
2717
  const defaults2 = proposed?.defaults ?? runtime.getDefaultModelOptions();
1805
- const readOption = (key) => resolveNestedOption((path2, fallback) => (0, import_utils12.get)(targetOptions, path2, fallback), key, (0, import_utils12.get)(defaults2, key));
2718
+ const readOption = (key) => resolveNestedOption((path2, fallback) => (0, import_utils13.get)(targetOptions, path2, fallback), key, (0, import_utils13.get)(defaults2, key));
1806
2719
  const documentPermissionField = targetOptions.documentPermissionField ?? defaults2.documentPermissionField;
1807
2720
  const catalog = captureAuthorizationFieldCatalog(targetModel.schema, void 0, documentPermissionField);
1808
2721
  const configuration = copyAuthorizationValue(
@@ -1812,7 +2725,12 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, populat
1812
2725
  populatePolicyDefaults,
1813
2726
  ...resolvePopulatePolicy(targetOptions, populatePolicyDefaults),
1814
2727
  permissionSchema: targetOptions.permissionSchema,
1815
- operationAccess: { read: readOption("operationAccess.read") },
2728
+ operationAccess: {
2729
+ read: selectOperationAccessGuard({
2730
+ ...createOperationAccessReaders(targetOptions, defaults2),
2731
+ baseAccess: "read"
2732
+ })
2733
+ },
1816
2734
  baseFilter: { read: readOption("baseFilter.read") },
1817
2735
  overrideFilter: { read: readOption("overrideFilter.read") },
1818
2736
  hydration: targetOptions.hydration
@@ -1860,13 +2778,13 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, populat
1860
2778
  );
1861
2779
  continue;
1862
2780
  }
1863
- if (!(0, import_utils12.isPlainObject)(raw)) continue;
2781
+ if (!(0, import_utils13.isPlainObject)(raw)) continue;
1864
2782
  const entry = raw;
1865
2783
  const label = join(sourcePrefix, name);
1866
2784
  captureList(entry.dependsOnPopulate, label);
1867
2785
  if (!("get" in entry))
1868
2786
  for (const access of accesses) {
1869
- if ((0, import_utils12.isPlainObject)(entry[access]))
2787
+ if ((0, import_utils13.isPlainObject)(entry[access]))
1870
2788
  captureList(entry[access].dependsOnPopulate, `${label}.${access}`);
1871
2789
  }
1872
2790
  const byAccess = {};
@@ -1892,18 +2810,97 @@ function captureVirtualPopulateDependencies(runtime, modelName, options, populat
1892
2810
  return Object.freeze({ scopes: Object.freeze(scopes) });
1893
2811
  }
1894
2812
 
2813
+ // src/acl/document-permissions-definition.ts
2814
+ var import_node_util10 = require("util");
2815
+
2816
+ // src/acl/persisted-dependencies.ts
2817
+ var import_node_util9 = require("util");
2818
+ function collectPersistedTopLevel(schema) {
2819
+ return /* @__PURE__ */ new Set([
2820
+ ...Object.keys(schema?.paths ?? {}).map((path) => path.split(".")[0]),
2821
+ ...Object.keys(schema?.obj ?? {})
2822
+ ]);
2823
+ }
2824
+ function capturePersistedDependencies(value, label, storedFields, virtualNames = /* @__PURE__ */ new Set()) {
2825
+ if (value === void 0) return Object.freeze([]);
2826
+ if (!Array.isArray(value) || import_node_util9.types.isProxy(value) || Object.getPrototypeOf(value) !== Array.prototype)
2827
+ throw new TypeError(`${label}: dependsOn must be an array of top-level persisted field names`);
2828
+ const length = Object.getOwnPropertyDescriptor(value, "length").value;
2829
+ if (length > 2e4 || Reflect.ownKeys(value).length !== length + 1)
2830
+ throw new TypeError(`${label}: dependsOn must be a dense array of persisted field names`);
2831
+ const result = [];
2832
+ for (let index = 0; index < length; index++) {
2833
+ const slot = Object.getOwnPropertyDescriptor(value, String(index));
2834
+ if (!slot || !("value" in slot) || typeof slot.value !== "string" || !slot.value)
2835
+ throw new TypeError(`${label}: dependsOn entries must be non-empty strings`);
2836
+ const dep = slot.value;
2837
+ if (dep.includes("."))
2838
+ throw new TypeError(`${label}: dependsOn "${dep}" must be a top-level persisted name (dotted paths rejected)`);
2839
+ if (!isSafeOutputPath(dep)) throw new TypeError(`${label}: unsafe dependsOn field "${dep}"`);
2840
+ if (virtualNames.has(dep)) throw new TypeError(`${label}: dependsOn "${dep}" must not reference another virtual`);
2841
+ if (storedFields && !storedFields.has(dep))
2842
+ throw new TypeError(`${label}: dependsOn "${dep}" is not a persisted field in its scope`);
2843
+ result.push(dep);
2844
+ }
2845
+ return Object.freeze([...new Set(result)]);
2846
+ }
2847
+
2848
+ // src/acl/document-permissions-definition.ts
2849
+ function dataRecord(value, label) {
2850
+ if (!value || typeof value !== "object" || import_node_util10.types.isProxy(value))
2851
+ throw new TypeError(`${label}: expected a function, { get, dependsOn? }, or per-access record`);
2852
+ const prototype = Object.getPrototypeOf(value);
2853
+ if (prototype !== Object.prototype && prototype !== null)
2854
+ throw new TypeError(`${label}: definition must be a plain object`);
2855
+ const result = /* @__PURE__ */ Object.create(null);
2856
+ const keys2 = Reflect.ownKeys(value);
2857
+ if (keys2.length > 2e4) throw new TypeError(`${label}: too many definition entries`);
2858
+ for (const key of keys2) {
2859
+ if (typeof key !== "string" || ["__proto__", "constructor", "prototype"].includes(key))
2860
+ throw new TypeError(`${label}: unsafe definition key`);
2861
+ const slot = Object.getOwnPropertyDescriptor(value, key);
2862
+ if (!slot.enumerable || !("value" in slot))
2863
+ throw new TypeError(`${label}: definition entries must be enumerable data properties`);
2864
+ Object.defineProperty(result, key, { value: slot.value, enumerable: true });
2865
+ }
2866
+ return result;
2867
+ }
2868
+ function captureLeaf(value, label, scope) {
2869
+ if (typeof value === "function") return value;
2870
+ const record2 = dataRecord(value, label);
2871
+ if (typeof record2.get !== "function") throw new TypeError(`${label}: descriptor.get must be callable`);
2872
+ if (Object.keys(record2).some((key) => key !== "get" && key !== "dependsOn"))
2873
+ throw new TypeError(`${label}: descriptor accepts only get/dependsOn; cannot mix per-access keys`);
2874
+ return Object.freeze({
2875
+ get: record2.get,
2876
+ dependsOn: capturePersistedDependencies(record2.dependsOn, label, scope.storedFields, scope.virtualNames)
2877
+ });
2878
+ }
2879
+ function captureDocumentPermissionsDefinition(value, scope = {}) {
2880
+ if (value === void 0) return void 0;
2881
+ if (typeof value === "function") return value;
2882
+ const record2 = dataRecord(value, "docPermissions");
2883
+ if (Object.hasOwn(record2, "get") || Object.hasOwn(record2, "dependsOn"))
2884
+ return captureLeaf(record2, "docPermissions", scope);
2885
+ const entries = Object.entries(record2).map(([access, leaf]) => {
2886
+ if (!/^[A-Za-z_][A-Za-z0-9_$]*$/.test(access))
2887
+ throw new TypeError(`docPermissions: unsafe or dotted access "${access}"`);
2888
+ return [access, leaf === void 0 ? void 0 : captureLeaf(leaf, `docPermissions.${access}`, scope)];
2889
+ });
2890
+ return Object.freeze(Object.fromEntries(entries));
2891
+ }
2892
+
1895
2893
  // src/runtime.ts
1896
2894
  var mongooseJsonSchemaInitialized = false;
1897
2895
  var ensureMongooseJsonSchemaInitialized = () => {
1898
2896
  if (mongooseJsonSchemaInitialized) return;
1899
- (0, import_mongoose_schema_jsonschema.default)(import_mongoose3.default);
2897
+ (0, import_mongoose_schema_jsonschema.default)(import_mongoose4.default);
1900
2898
  mongooseJsonSchemaInitialized = true;
1901
2899
  };
1902
- var pluralize = import_mongoose3.default.pluralize();
2900
+ var pluralize = import_mongoose4.default.pluralize();
1903
2901
  var FIELD_ACCESS_KEYS = ["list", "create", "read", "update"];
1904
2902
  var defaultModelOptions = {
1905
- basePath: null,
1906
- alwaysSelectFields: []
2903
+ basePath: null
1907
2904
  };
1908
2905
  var modelOverrides = (options) => {
1909
2906
  const result = Object.fromEntries(
@@ -1911,7 +2908,6 @@ var modelOverrides = (options) => {
1911
2908
  ([key, value]) => value !== void 0 || key === "operationAccess" || isPopulatePolicyKey(key)
1912
2909
  )
1913
2910
  );
1914
- for (const key of unsafeServerOptions) if (key in result) result[key] = result[key] === true;
1915
2911
  return cloneOptionsSnapshot(result);
1916
2912
  };
1917
2913
  var defaultDataOptions = {
@@ -1921,44 +2917,44 @@ var defaultDataOptions = {
1921
2917
  listHardLimit: DEFAULT_LIST_HARD_LIMIT
1922
2918
  };
1923
2919
  var normalizeBasePath = (name, value) => {
1924
- if ((0, import_utils13.isNil)(value)) {
2920
+ if ((0, import_utils14.isNil)(value)) {
1925
2921
  return `/${pluralize(name)}`;
1926
2922
  }
1927
- return (0, import_utils13.isString)(value) ? (0, import_utils13.addLeadingSlash)(value) : "";
2923
+ return (0, import_utils14.isString)(value) ? (0, import_utils14.addLeadingSlash)(value) : "";
1928
2924
  };
1929
2925
  var hasModelPermission = (value, modelPermissionPrefix) => {
1930
2926
  if (!modelPermissionPrefix) {
1931
2927
  return true;
1932
2928
  }
1933
- if ((0, import_utils13.isString)(value)) {
2929
+ if ((0, import_utils14.isString)(value)) {
1934
2930
  return value.trim().split(" ").some((item) => item.startsWith(modelPermissionPrefix));
1935
2931
  }
1936
- if ((0, import_utils13.isArray)(value)) {
2932
+ if ((0, import_utils14.isArray)(value)) {
1937
2933
  return value.some((item) => {
1938
- if ((0, import_utils13.isString)(item) || (0, import_utils13.isArray)(item)) {
2934
+ if ((0, import_utils14.isString)(item) || (0, import_utils14.isArray)(item)) {
1939
2935
  return hasModelPermission(item, modelPermissionPrefix);
1940
2936
  }
1941
2937
  return true;
1942
2938
  });
1943
2939
  }
1944
- return (0, import_utils13.isFunction)(value);
2940
+ return (0, import_utils14.isFunction)(value);
1945
2941
  };
1946
2942
  var classifyPermissionSchema = (permissionSchema, modelPermissionPrefix) => {
1947
2943
  const schemaKeys = Object.keys(permissionSchema);
1948
2944
  const globalPermissionKeys = {};
1949
2945
  const modelPermissionKeys = {};
1950
- (0, import_utils13.forEach)(schemaKeys, (schemaKey) => {
2946
+ (0, import_utils14.forEach)(schemaKeys, (schemaKey) => {
1951
2947
  const schemaRule = permissionSchema[schemaKey];
1952
- const ruleEntries = (0, import_utils13.isPlainObject)(schemaRule) ? Object.entries(schemaRule) : FIELD_ACCESS_KEYS.map((accessKey) => [accessKey, schemaRule]);
2948
+ const ruleEntries = (0, import_utils14.isPlainObject)(schemaRule) ? Object.entries(schemaRule) : FIELD_ACCESS_KEYS.map((accessKey) => [accessKey, schemaRule]);
1953
2949
  for (let x = 0; x < ruleEntries.length; x++) {
1954
2950
  const [accessKey, value] = ruleEntries[x];
1955
- if (!(0, import_utils13.isArray)(globalPermissionKeys[accessKey])) {
2951
+ if (!(0, import_utils14.isArray)(globalPermissionKeys[accessKey])) {
1956
2952
  globalPermissionKeys[accessKey] = [];
1957
2953
  }
1958
- if (!(0, import_utils13.isArray)(modelPermissionKeys[accessKey])) {
2954
+ if (!(0, import_utils14.isArray)(modelPermissionKeys[accessKey])) {
1959
2955
  modelPermissionKeys[accessKey] = [];
1960
2956
  }
1961
- if ((0, import_utils13.isBoolean)(value)) {
2957
+ if ((0, import_utils14.isBoolean)(value)) {
1962
2958
  globalPermissionKeys[accessKey].push(schemaKey);
1963
2959
  continue;
1964
2960
  }
@@ -1990,34 +2986,19 @@ var VIRTUAL_UNSUPPORTED_ACCESSES = ["delete", "distinct", "count"];
1990
2986
  var VIRTUAL_RESERVED_NAMES = /* @__PURE__ */ new Set(["_id", "__v", "id"]);
1991
2987
  var VIRTUAL_DANGEROUS_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
1992
2988
  var VIRTUAL_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_$]*$/;
1993
- var isVirtualContainerValue2 = (value) => (0, import_utils13.isPlainObject)(value) && "sub" in value;
2989
+ var isVirtualContainerValue2 = (value) => (0, import_utils14.isPlainObject)(value) && "sub" in value;
1994
2990
  var virtualFullPath = (prefix, name) => prefix ? `${prefix}.${name}` : name;
1995
2991
  var virtualPathsOverlap = (virtualPath, permissionField) => {
1996
2992
  if (!virtualPath || !permissionField) return false;
1997
2993
  try {
1998
- if ((0, import_utils13.get)((0, import_utils13.set)({}, virtualPath, true), permissionField) !== void 0) return true;
1999
- if ((0, import_utils13.get)((0, import_utils13.set)({}, permissionField, true), virtualPath) !== void 0) return true;
2994
+ if ((0, import_utils14.get)((0, import_utils14.set)({}, virtualPath, true), permissionField) !== void 0) return true;
2995
+ if ((0, import_utils14.get)((0, import_utils14.set)({}, permissionField, true), virtualPath) !== void 0) return true;
2000
2996
  } catch {
2001
2997
  return false;
2002
2998
  }
2003
2999
  return false;
2004
3000
  };
2005
- var collectStoredTopLevel = (schema) => {
2006
- const fields = /* @__PURE__ */ new Set();
2007
- if (!schema) return fields;
2008
- const paths = schema.paths;
2009
- if (paths) {
2010
- for (const p of Object.keys(paths)) {
2011
- const top = p.split(".")[0];
2012
- if (top) fields.add(top);
2013
- }
2014
- }
2015
- const obj = schema.obj;
2016
- if (obj) {
2017
- for (const k of Object.keys(obj)) fields.add(k);
2018
- }
2019
- return fields;
2020
- };
3001
+ var collectStoredTopLevel = collectPersistedTopLevel;
2021
3002
  var getChildSchemaForField = (parentSchema, fieldName) => {
2022
3003
  if (!parentSchema) return null;
2023
3004
  try {
@@ -2056,40 +3037,15 @@ var cloneModelOptionForUpdate = (value) => {
2056
3037
  );
2057
3038
  };
2058
3039
  var validateVirtualDependsOn = (dependsOn, entryLabel, storedFields, siblingVirtualNames) => {
2059
- if (dependsOn === void 0) return [];
2060
- if (!(0, import_utils13.isArray)(dependsOn)) {
2061
- throw new Error(`Virtual ${entryLabel}: dependsOn must be an array of top-level persisted field names`);
2062
- }
2063
- const list = dependsOn;
2064
- for (const dep of list) {
2065
- if (!(0, import_utils13.isString)(dep) || dep.length === 0) {
2066
- throw new Error(`Virtual ${entryLabel}: dependsOn entries must be non-empty strings`);
2067
- }
2068
- if (dep.includes(".")) {
2069
- throw new Error(
2070
- `Virtual ${entryLabel}: dependsOn "${dep}" must be a top-level persisted name relative to its scope (dotted paths rejected)`
2071
- );
2072
- }
2073
- if (siblingVirtualNames.has(dep)) {
2074
- throw new Error(
2075
- `Virtual ${entryLabel}: dependsOn "${dep}" must not reference another virtual (virtual-to-virtual rejected)`
2076
- );
2077
- }
2078
- if (!storedFields.has(dep)) {
2079
- throw new Error(
2080
- `Virtual ${entryLabel}: dependsOn "${dep}" is not a persisted field in its scope (validated against the receiving Mongoose schema/child scope)`
2081
- );
2082
- }
2083
- }
2084
- return list;
3040
+ return [...capturePersistedDependencies(dependsOn, `Virtual ${entryLabel}`, storedFields, siblingVirtualNames)];
2085
3041
  };
2086
3042
  var validateVirtualLeafValue = (value, entryLabel, storedFields, siblingVirtualNames, sharedDependsOn) => {
2087
- if ((0, import_utils13.isFunction)(value)) return;
2088
- if (!(0, import_utils13.isPlainObject)(value)) {
3043
+ if ((0, import_utils14.isFunction)(value)) return;
3044
+ if (!(0, import_utils14.isPlainObject)(value)) {
2089
3045
  throw new Error(`Virtual ${entryLabel}: descriptor must be a getter function or { get, dependsOn }`);
2090
3046
  }
2091
3047
  const record2 = value;
2092
- if (!(0, import_utils13.isFunction)(record2.get)) {
3048
+ if (!(0, import_utils14.isFunction)(record2.get)) {
2093
3049
  throw new Error(`Virtual ${entryLabel}: descriptor.get must be a callable getter function`);
2094
3050
  }
2095
3051
  validateVirtualDependsOn(record2.dependsOn ?? sharedDependsOn, entryLabel, storedFields, siblingVirtualNames);
@@ -2131,7 +3087,7 @@ var validateVirtualsScope = (scope, documentPermissionField) => {
2131
3087
  `Virtual ${scopeLabel}${name}: scope-container must only hold "sub" (embedded container "${name}" is not a virtual-leaf collision)`
2132
3088
  );
2133
3089
  }
2134
- if (!(0, import_utils13.isPlainObject)(record3.sub)) {
3090
+ if (!(0, import_utils14.isPlainObject)(record3.sub)) {
2135
3091
  throw new Error(`Virtual ${scopeLabel}${name}: scope-container "sub" must be a plain object`);
2136
3092
  }
2137
3093
  continue;
@@ -2141,8 +3097,8 @@ var validateVirtualsScope = (scope, documentPermissionField) => {
2141
3097
  `Virtual ${scopeLabel}${name}: collides with a stored path (inspected actual Mongoose schema/child scope; getModelAtt alone is insufficient)`
2142
3098
  );
2143
3099
  }
2144
- if ((0, import_utils13.isFunction)(raw)) continue;
2145
- if (!(0, import_utils13.isPlainObject)(raw)) {
3100
+ if ((0, import_utils14.isFunction)(raw)) continue;
3101
+ if (!(0, import_utils14.isPlainObject)(raw)) {
2146
3102
  throw new Error(
2147
3103
  `Virtual ${scopeLabel}${name}: malformed descriptor (expected getter, { get, dependsOn }, or per-access record)`
2148
3104
  );
@@ -2196,7 +3152,7 @@ var validateVirtualsScope = (scope, documentPermissionField) => {
2196
3152
  };
2197
3153
  var validateVirtualsTree = (model, virtuals, documentPermissionField, modelName) => {
2198
3154
  if (virtuals === void 0 || virtuals === null) return;
2199
- if (!(0, import_utils13.isPlainObject)(virtuals)) {
3155
+ if (!(0, import_utils14.isPlainObject)(virtuals)) {
2200
3156
  throw new Error(`Virtuals for model "${modelName}": virtuals must be a plain object mapping names to descriptors`);
2201
3157
  }
2202
3158
  const rootSchema = model?.schema ?? null;
@@ -2256,6 +3212,7 @@ var AccessRuntime = class {
2256
3212
  this.defaultModelOptions = new OptionsManager({
2257
3213
  listHardLimit: DEFAULT_LIST_HARD_LIMIT,
2258
3214
  documentPermissionField: "_permissions",
3215
+ disableFieldPermissions: true,
2259
3216
  idParam: "id",
2260
3217
  idField: "_id",
2261
3218
  parentPath: "/",
@@ -2265,19 +3222,14 @@ var AccessRuntime = class {
2265
3222
  requireOperationAccessForPopulateQueries: true,
2266
3223
  requireOperationAccessForPopulateDependencies: true,
2267
3224
  modelPermissionPrefix: "",
2268
- unsafeSkipListDocumentSnapshotChecks: false,
2269
- unsafeSkipReadDocumentSnapshotChecks: false,
2270
- unsafeSkipListOutputSnapshotChecks: false,
2271
- unsafeSkipReadOutputSnapshotChecks: false,
2272
- unsafeSkipListNestedDocumentSnapshotChecks: false,
2273
- unsafeSkipReadNestedDocumentSnapshotChecks: false,
2274
- unsafeSkipListInitialOutputSnapshotCopy: false,
2275
- unsafeSkipReadInitialOutputSnapshotCopy: false,
2276
- unsafeUseListAuthorizationFastPath: false,
2277
- unsafeUseReadAuthorizationFastPath: false
3225
+ readAuthorizationMode: "isolated",
3226
+ listAuthorizationMode: "isolated",
3227
+ createAuthorizationMode: "isolated",
3228
+ updateAuthorizationMode: "isolated"
2278
3229
  }).build();
2279
3230
  this.modelOptions = {};
2280
3231
  this.modelOptionOverrides = {};
3232
+ this.publishingAuthorizationModes = false;
2281
3233
  this.modelJsonSchemas = {};
2282
3234
  this.dataOptions = {};
2283
3235
  this.modelRefs = {};
@@ -2286,6 +3238,10 @@ var AccessRuntime = class {
2286
3238
  this.modelInstances = {};
2287
3239
  this.openApiRegistry = new OpenApiRegistry();
2288
3240
  this.openApiPathPrefix = "";
3241
+ assertAuthorizationModeOptions(options, false);
3242
+ assertNoServerModelControls(options, (detail) => {
3243
+ throw new TypeError(detail);
3244
+ });
2289
3245
  this.allowGlobalModelLookup = options.allowGlobalModelLookup ?? false;
2290
3246
  ensureMongooseJsonSchemaInitialized();
2291
3247
  }
@@ -2302,20 +3258,20 @@ var AccessRuntime = class {
2302
3258
  this.modelInstances[modelName] = model;
2303
3259
  }
2304
3260
  hasModelInstance(modelName) {
2305
- return modelName in this.modelInstances || this.allowGlobalModelLookup && modelName in import_mongoose3.default.models;
3261
+ return modelName in this.modelInstances || this.allowGlobalModelLookup && modelName in import_mongoose4.default.models;
2306
3262
  }
2307
3263
  getModelInstance(modelName) {
2308
3264
  const registered = this.modelInstances[modelName];
2309
3265
  if (registered) return registered;
2310
3266
  if (!this.allowGlobalModelLookup) return null;
2311
- const global = import_mongoose3.default.models[modelName];
3267
+ const global = import_mongoose4.default.models[modelName];
2312
3268
  if (!global) return null;
2313
3269
  this.registerModelInstance(modelName, global);
2314
3270
  return global;
2315
3271
  }
2316
3272
  registerOpenApiRoute(route) {
2317
3273
  this.openApiRegistry.register(
2318
- this.openApiPathPrefix ? { ...route, path: (0, import_utils13.normalizeUrlPath)(`${this.openApiPathPrefix}/${route.path}`) } : route
3274
+ this.openApiPathPrefix ? { ...route, path: (0, import_utils14.normalizeUrlPath)(`${this.openApiPathPrefix}/${route.path}`) } : route
2319
3275
  );
2320
3276
  }
2321
3277
  /**
@@ -2326,7 +3282,7 @@ var AccessRuntime = class {
2326
3282
  */
2327
3283
  withOpenApiPathPrefix(prefix, build) {
2328
3284
  const previous = this.openApiPathPrefix;
2329
- this.openApiPathPrefix = (0, import_utils13.normalizeUrlPath)(`${previous}/${prefix}`);
3285
+ this.openApiPathPrefix = (0, import_utils14.normalizeUrlPath)(`${previous}/${prefix}`);
2330
3286
  try {
2331
3287
  return build();
2332
3288
  } finally {
@@ -2378,6 +3334,52 @@ var AccessRuntime = class {
2378
3334
  };
2379
3335
  }
2380
3336
  restoreBootstrapSnapshot(snapshot) {
3337
+ assertAuthorizationModeOptions(snapshot, false);
3338
+ const reject = (detail) => {
3339
+ throw new TypeError(detail);
3340
+ };
3341
+ for (const key of [
3342
+ "globalOptions",
3343
+ "defaultModelOptions",
3344
+ "modelOptions",
3345
+ "modelOptionOverrides",
3346
+ "dataOptions",
3347
+ "modelInstances",
3348
+ "modelJsonSchemas",
3349
+ "modelRefs",
3350
+ "modelSubs",
3351
+ "modelAtts",
3352
+ "openApi"
3353
+ ]) {
3354
+ const slot = Object.getOwnPropertyDescriptor(snapshot, key);
3355
+ if (!slot || !("value" in slot) || !slot.enumerable) reject(`Invalid bootstrap snapshot slot: ${key}`);
3356
+ if (!slot.value || typeof slot.value !== "object" || Array.isArray(slot.value))
3357
+ reject(`Invalid bootstrap snapshot object: ${key}`);
3358
+ admitControlPrototypes(slot.value, reject);
3359
+ if (key === "globalOptions" || key === "defaultModelOptions" || key === "openApi") continue;
3360
+ for (const entry of Reflect.ownKeys(slot.value)) {
3361
+ const item = Object.getOwnPropertyDescriptor(slot.value, entry);
3362
+ if (typeof entry !== "string" || !("value" in item) || !item.enumerable)
3363
+ reject(`Invalid bootstrap snapshot entry: ${key}`);
3364
+ }
3365
+ }
3366
+ assertAuthorizationModeOptions(snapshot.globalOptions, false);
3367
+ assertNoServerModelControls(snapshot.globalOptions, reject);
3368
+ assertAuthorizationModeOptions(snapshot.defaultModelOptions, true);
3369
+ assertOperationAccessOptions(snapshot.defaultModelOptions);
3370
+ assertNoServerModelControls(snapshot.defaultModelOptions, reject, "model-options");
3371
+ assertPublicDefaults(snapshot.defaultModelOptions.defaults);
3372
+ for (const options of [...Object.values(snapshot.modelOptions), ...Object.values(snapshot.modelOptionOverrides)]) {
3373
+ assertAuthorizationModeOptions(options, true);
3374
+ assertOperationAccessOptions(options);
3375
+ assertNoServerModelControls(options, reject, "model-options");
3376
+ assertPublicDefaults(options.defaults);
3377
+ }
3378
+ for (const options of Object.values(snapshot.dataOptions)) {
3379
+ assertAuthorizationModeOptions(options, false);
3380
+ assertOperationAccessOptions(options);
3381
+ assertNoServerModelControls(options, reject, "data-options");
3382
+ }
2381
3383
  this.globalOptions.restore(snapshot.globalOptions);
2382
3384
  this.defaultModelOptions.restore(snapshot.defaultModelOptions);
2383
3385
  for (const name of Object.keys(this.modelOptionOverrides)) delete this.modelOptionOverrides[name];
@@ -2437,11 +3439,21 @@ var AccessRuntime = class {
2437
3439
  }
2438
3440
  /** Shallowly replace supplied global values; nested objects such as requestComplexity are not deep-merged. */
2439
3441
  setGlobalOptions(options) {
3442
+ assertAuthorizationModeOptions(options, false);
3443
+ assertNoServerModelControls(options, (detail) => {
3444
+ throw new TypeError(detail);
3445
+ });
2440
3446
  for (const key of populatePolicyKeys) if (key in options) assertNoGlobalPopulatePolicy(key);
2441
3447
  this.globalOptions.assign({ ...options });
2442
3448
  }
2443
3449
  setGlobalOption(key, value) {
3450
+ assertAuthorizationModeKey(key, false);
2444
3451
  assertNoGlobalPopulatePolicy(String(key));
3452
+ const proposed = {};
3453
+ (0, import_utils14.set)(proposed, key, value);
3454
+ assertNoServerModelControls(proposed, (detail) => {
3455
+ throw new TypeError(detail);
3456
+ });
2445
3457
  this.globalOptions.set(key, value);
2446
3458
  }
2447
3459
  getGlobalOptions() {
@@ -2452,6 +3464,18 @@ var AccessRuntime = class {
2452
3464
  }
2453
3465
  /** Update inherited model defaults shallowly. Explicit model values and captured calls are unchanged. */
2454
3466
  setDefaultModelOptions(options) {
3467
+ assertAuthorizationModeOptions(options, true);
3468
+ assertOperationAccessOptions(options);
3469
+ assertNoServerModelControls(
3470
+ options,
3471
+ (detail) => {
3472
+ throw new TypeError(detail);
3473
+ },
3474
+ "model-options"
3475
+ );
3476
+ options = { ...options };
3477
+ for (const key of authorizationModeKeys)
3478
+ if (key in options && options[key] === void 0) options[key] = "isolated";
2455
3479
  assertPublicDefaults(options.defaults);
2456
3480
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
2457
3481
  const draft = new OptionsManager(
@@ -2461,11 +3485,32 @@ var AccessRuntime = class {
2461
3485
  this.publishDefaultModelOptions(draft.fetch());
2462
3486
  }
2463
3487
  setDefaultModelOption(key, value) {
2464
- const keyStr = String(key);
2465
- if (keyStr === "defaults") assertPublicDefaults(value);
2466
- else if (keyStr.startsWith("defaults.")) {
3488
+ assertAuthorizationModeKey(key, true);
3489
+ const keyStr = key;
3490
+ assertOperationAccessUpdate(keyStr, value);
3491
+ if (authorizationModeKeys.includes(keyStr)) {
3492
+ this.setDefaultModelOptions({ [keyStr]: value });
3493
+ return;
3494
+ }
3495
+ if (keyStr === "defaults") {
3496
+ assertNoServerModelControls(
3497
+ value,
3498
+ (detail) => {
3499
+ throw new TypeError(detail);
3500
+ },
3501
+ "defaults"
3502
+ );
3503
+ assertPublicDefaults(value);
3504
+ } else if (keyStr.startsWith("defaults.")) {
2467
3505
  const proposed = {};
2468
- (0, import_utils13.set)(proposed, keyStr.slice("defaults.".length), value);
3506
+ (0, import_utils14.set)(proposed, keyStr.slice("defaults.".length), value);
3507
+ assertNoServerModelControls(
3508
+ proposed,
3509
+ (detail) => {
3510
+ throw new TypeError(detail);
3511
+ },
3512
+ "defaults"
3513
+ );
2469
3514
  assertPublicDefaults(proposed);
2470
3515
  }
2471
3516
  const draft = new OptionsManager(
@@ -2492,92 +3537,62 @@ var AccessRuntime = class {
2492
3537
  for (const key of populatePolicyKeys) delete inherited[key];
2493
3538
  const effective = { ...defaultModelOptions, ...inherited, ...overrides, modelName };
2494
3539
  effective.basePath = normalizeBasePath(modelName, effective.basePath);
2495
- for (const key of unsafeServerOptions) effective[key] = effective[key] === true;
2496
3540
  refreshPermissionMetadata(effective);
2497
3541
  return cloneOptionsSnapshot(effective);
2498
3542
  }
2499
3543
  validateModelOptions(modelName, options, proposed) {
2500
- validateVirtualsTree(
2501
- this.getModelInstance(modelName),
2502
- options.virtuals,
2503
- options.documentPermissionField ?? "_permissions",
2504
- modelName
2505
- );
3544
+ assertOperationAccessOptions(options);
3545
+ const model = this.getModelInstance(modelName);
3546
+ validateVirtualsTree(model, options.virtuals, options.documentPermissionField ?? "_permissions", modelName);
3547
+ captureDocumentPermissionsDefinition(options.docPermissions, {
3548
+ storedFields: collectPersistedTopLevel(model?.schema),
3549
+ virtualNames: /* @__PURE__ */ new Set([
3550
+ ...Object.keys(model?.schema.virtuals ?? {}),
3551
+ ...Object.entries(options.virtuals ?? {}).filter(([, value]) => value !== void 0 && !isVirtualContainerValue2(value)).map(([name]) => name)
3552
+ ])
3553
+ });
2506
3554
  captureVirtualPopulateDependencies(this, modelName, options, void 0, proposed);
2507
3555
  }
2508
3556
  publishDefaultModelOptions(options) {
3557
+ assertOperationAccessOptions(options);
2509
3558
  const next = { ...options };
2510
- for (const key of unsafeServerOptions) if (key in next) next[key] = next[key] === true;
2511
3559
  const defaults2 = cloneOptionsSnapshot(next);
2512
3560
  const models = new Map(
2513
3561
  Object.keys(this.modelOptions).map((name) => [name, this.resolveModelOptions(name, void 0, defaults2)])
2514
3562
  );
2515
3563
  for (const [name, options2] of models) this.validateModelOptions(name, options2, { defaults: defaults2, models });
2516
- this.deferSnapshotWarnings(() => {
3564
+ this.publishAuthorizationModes(() => {
2517
3565
  this.defaultModelOptions.restore(defaults2);
2518
3566
  for (const [name, options2] of models) this.modelOptions[name].restore(options2);
2519
3567
  });
2520
3568
  }
2521
- warnSnapshotFlag(modelName, key) {
2522
- if (this.pendingSnapshotWarnings) {
2523
- this.pendingSnapshotWarnings.push({ modelName, key });
2524
- return;
2525
- }
2526
- const operation = key.startsWith("unsafeSkipRead") ? "read" : "list";
2527
- const category = key.includes("NestedDocument") ? "nested-document" : key.includes("Output") ? "output" : "document";
2528
- const risk = category === "output" ? "output mutation" : "source mutation";
2529
- try {
2530
- this.getGlobalOption("logger")?.warn?.(
2531
- `UNSAFE: ${operation} ${category} snapshot checks disabled; ${risk} can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
2532
- { modelName }
2533
- );
2534
- } catch {
2535
- }
2536
- }
2537
- deferSnapshotWarnings(publish) {
2538
- if (this.pendingSnapshotWarnings) return publish();
2539
- const copyModes = this.initialOutputCopyModes();
2540
- const fastModes = this.authorizationFastPathModes();
2541
- const pending = [];
2542
- this.pendingSnapshotWarnings = pending;
3569
+ /** Warn only on effective transitions into trusted, after the entire update commits. */
3570
+ publishAuthorizationModes(publish) {
3571
+ if (this.publishingAuthorizationModes) return publish();
3572
+ const capture = () => new Map([
3573
+ ["default-model", this.getDefaultModelOptions()],
3574
+ ...Object.entries(this.modelOptions).map(([name, manager]) => [name, manager.fetch()])
3575
+ ]);
3576
+ const before = capture();
3577
+ this.publishingAuthorizationModes = true;
2543
3578
  let result;
2544
3579
  try {
2545
3580
  result = publish();
2546
3581
  } finally {
2547
- this.pendingSnapshotWarnings = void 0;
2548
- }
2549
- const nextCopyModes = this.initialOutputCopyModes();
2550
- const nextFastModes = this.authorizationFastPathModes();
2551
- for (const { modelName, key } of pending) this.warnSnapshotFlag(modelName, key);
2552
- for (const [modelName, modes] of nextCopyModes) {
2553
- for (const operation of ["List", "Read"]) {
2554
- const mode = modes[operation];
2555
- if (mode === "off" || mode === copyModes.get(modelName)?.[operation]) continue;
2556
- const key = `unsafeSkip${operation}InitialOutputSnapshotCopy`;
2557
- const prerequisite = `unsafeSkip${operation}OutputSnapshotChecks`;
2558
- try {
2559
- this.getGlobalOption("logger")?.warn?.(
2560
- 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.`,
2561
- { modelName }
2562
- );
2563
- } catch {
2564
- }
2565
- }
3582
+ this.publishingAuthorizationModes = false;
2566
3583
  }
2567
- for (const [modelName, modes] of nextFastModes) {
2568
- for (const origin of ["list", "read"]) {
2569
- const captured = modes[origin];
2570
- const previous = fastModes.get(modelName)?.[origin];
2571
- if (captured.mode === "off" || captured.mode === previous?.mode && (captured.mode !== "dormant" || captured.prerequisites === previous.prerequisites))
2572
- continue;
2573
- const key = origin === "read" ? "unsafeUseReadAuthorizationFastPath" : "unsafeUseListAuthorizationFastPath";
2574
- const missing = authorizationFastPathPrerequisites(origin).filter(
2575
- (_, index) => !(captured.prerequisites & 1 << index)
2576
- );
3584
+ const after = capture();
3585
+ for (const [modelName, options] of after) {
3586
+ for (const key of authorizationModeKeys) {
3587
+ if (options[key] !== "trusted" || before.get(modelName)?.[key] === "trusted") continue;
2577
3588
  try {
2578
3589
  this.getGlobalOption("logger")?.warn?.(
2579
- captured.mode === "active" ? `UNSAFE: ${origin} authorization fast path active (${key}=true); eligible query rows borrow source/grant/context leaves and omit repeated snapshots, isolation and descendant graph checks. Borrowed source/grant mutation, stale decisions, descendant replacement, lost native normalization/validation observations and loss of full unvisited source shape/bounds can change authorization outcomes, including denial becoming allowance. Actual operation/row/field rules, document hooks/getters, request/work limits and cheap exact root authority remain; shallow-unproven rows retain compatible copies and graph checks. Restore ${key}=false after the temporary workaround.` : `UNSAFE: ${key} is dormant; requires ${missing.map((flag) => `${flag}=true`).join(", ")}. Original snapshot flag behavior remains unchanged. Restore ${key}=false if not intended.`,
2580
- { modelName }
3590
+ "Trusted authorization output source mode enabled; admitted source/document-hook input may be borrowed. Write input is unchanged. Actor, policy, facts, getter views and selected output bounds remain owned.",
3591
+ {
3592
+ modelName,
3593
+ access: authorizationModeOperations[key],
3594
+ category: "trustedAuthorizationSource"
3595
+ }
2581
3596
  );
2582
3597
  } catch {
2583
3598
  }
@@ -2585,25 +3600,6 @@ var AccessRuntime = class {
2585
3600
  }
2586
3601
  return result;
2587
3602
  }
2588
- authorizationFastPathModes() {
2589
- return new Map(
2590
- Object.entries(this.modelOptions).map(([modelName, manager]) => {
2591
- const options = manager.fetch();
2592
- return [
2593
- modelName,
2594
- { list: captureAuthorizationFastPath(options, "list"), read: captureAuthorizationFastPath(options, "read") }
2595
- ];
2596
- })
2597
- );
2598
- }
2599
- initialOutputCopyModes() {
2600
- return new Map(
2601
- Object.entries(this.modelOptions).map(([modelName, options]) => {
2602
- const mode = (operation) => options.get(`unsafeSkip${operation}InitialOutputSnapshotCopy`) !== true ? "off" : options.get(`unsafeSkip${operation}OutputSnapshotChecks`) === true ? "active" : "dormant";
2603
- return [modelName, { List: mode("List"), Read: mode("Read") }];
2604
- })
2605
- );
2606
- }
2607
3603
  createModelOptions(modelName, options = this.resolveModelOptions(modelName)) {
2608
3604
  const model = this.getModelInstance(modelName);
2609
3605
  if (!model) {
@@ -2612,19 +3608,14 @@ var AccessRuntime = class {
2612
3608
  );
2613
3609
  }
2614
3610
  const manager = new OptionsManager(options);
2615
- const snapshotFlagChanged = (newValue, key, target, oldValue) => {
2616
- target[key] = newValue === true;
2617
- if (newValue !== true || oldValue === true) return;
2618
- this.warnSnapshotFlag(modelName, key);
2619
- };
2620
3611
  manager.onchange("permissionSchema", function(_newval, _key, target) {
2621
3612
  refreshPermissionMetadata(target);
2622
3613
  }).onchange("modelPermissionPrefix", function(_newval, _key, target) {
2623
3614
  refreshPermissionMetadata(target);
2624
- }).onchange("unsafeSkipListDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipListOutputSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadOutputSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipListNestedDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadNestedDocumentSnapshotChecks", snapshotFlagChanged).onchange("basePath", function(newval, key, target) {
3615
+ }).onchange("basePath", function(newval, key, target) {
2625
3616
  target[key] = normalizeBasePath(
2626
3617
  modelName,
2627
- (0, import_utils13.isString)(newval) || (0, import_utils13.isNil)(newval) ? newval : void 0
3618
+ (0, import_utils14.isString)(newval) || (0, import_utils14.isNil)(newval) ? newval : void 0
2628
3619
  );
2629
3620
  }).build();
2630
3621
  this.modelJsonSchemas[modelName] = model.jsonSchema();
@@ -2633,7 +3624,7 @@ var AccessRuntime = class {
2633
3624
  getOrCreateModelOptions(modelName) {
2634
3625
  let manager = this.modelOptions[modelName];
2635
3626
  if (!manager) {
2636
- manager = this.deferSnapshotWarnings(() => {
3627
+ manager = this.publishAuthorizationModes(() => {
2637
3628
  const created = this.createModelOptions(modelName);
2638
3629
  this.modelOptions[modelName] = created;
2639
3630
  return created;
@@ -2650,13 +3641,28 @@ var AccessRuntime = class {
2650
3641
  * calls capture the owner's current options/defaults; in-flight calls retain their snapshot.
2651
3642
  */
2652
3643
  setModelOptions(modelName, options) {
3644
+ assertAuthorizationModeOptions(options, true);
3645
+ assertOperationAccessOptions(options);
3646
+ assertNoServerModelControls(
3647
+ options,
3648
+ (detail) => {
3649
+ throw new TypeError(detail);
3650
+ },
3651
+ "model-options"
3652
+ );
2653
3653
  assertPublicDefaults(options.defaults);
3654
+ if ("docPermissions" in options) {
3655
+ const slot = Object.getOwnPropertyDescriptor(options, "docPermissions");
3656
+ if (!slot || !("value" in slot) || !slot.enumerable)
3657
+ throw new TypeError("docPermissions must be an enumerable data property");
3658
+ options = { ...options, docPermissions: captureDocumentPermissionsDefinition(slot.value) };
3659
+ }
2654
3660
  options = normalizePopulatePolicyOptions(options);
2655
3661
  if ("hydration" in options) options = { ...options, hydration: normalizeHydration(options.hydration) };
2656
3662
  const overrides = modelOverrides({ ...this.modelOptionOverrides[modelName], ...options });
2657
3663
  const effective = this.resolveModelOptions(modelName, overrides);
2658
3664
  this.validateModelOptions(modelName, effective);
2659
- this.deferSnapshotWarnings(() => {
3665
+ this.publishAuthorizationModes(() => {
2660
3666
  const manager = this.modelOptions[modelName];
2661
3667
  if (manager) manager.restore(effective);
2662
3668
  else this.modelOptions[modelName] = this.createModelOptions(modelName, effective);
@@ -2664,16 +3670,43 @@ var AccessRuntime = class {
2664
3670
  });
2665
3671
  }
2666
3672
  setModelOption(modelName, key, value) {
2667
- const keyStr = String(key);
3673
+ assertAuthorizationModeKey(key, true);
3674
+ const keyStr = key;
3675
+ assertOperationAccessUpdate(keyStr, value);
3676
+ if (keyStr === "docPermissions") {
3677
+ value = captureDocumentPermissionsDefinition(value);
3678
+ } else if (keyStr.startsWith("docPermissions.")) {
3679
+ const path2 = keyStr.slice("docPermissions.".length);
3680
+ if (path2.includes(".") || path2 === "get" || path2 === "dependsOn")
3681
+ throw new TypeError(
3682
+ "docPermissions dotted setters replace an access definition; set { get, dependsOn? } together"
3683
+ );
3684
+ captureDocumentPermissionsDefinition({ [path2]: value });
3685
+ }
2668
3686
  if (keyStr === "hydration" || keyStr.startsWith("hydration.")) {
2669
3687
  const hydration = normalizeHydrationUpdate(this.resolveModelOptions(modelName).hydration, keyStr, value);
2670
3688
  this.setModelOptions(modelName, { hydration });
2671
3689
  return;
2672
3690
  }
2673
- if (keyStr === "defaults") assertPublicDefaults(value);
2674
- else if (keyStr.startsWith("defaults.")) {
3691
+ if (keyStr === "defaults") {
3692
+ assertNoServerModelControls(
3693
+ value,
3694
+ (detail) => {
3695
+ throw new TypeError(detail);
3696
+ },
3697
+ "defaults"
3698
+ );
3699
+ assertPublicDefaults(value);
3700
+ } else if (keyStr.startsWith("defaults.")) {
2675
3701
  const proposed = {};
2676
- (0, import_utils13.set)(proposed, keyStr.slice("defaults.".length), value);
3702
+ (0, import_utils14.set)(proposed, keyStr.slice("defaults.".length), value);
3703
+ assertNoServerModelControls(
3704
+ proposed,
3705
+ (detail) => {
3706
+ throw new TypeError(detail);
3707
+ },
3708
+ "defaults"
3709
+ );
2677
3710
  assertPublicDefaults(proposed);
2678
3711
  }
2679
3712
  const [root, ...path] = keyStr.split(".");
@@ -2682,11 +3715,14 @@ var AccessRuntime = class {
2682
3715
  return;
2683
3716
  }
2684
3717
  const current = this.resolveModelOptions(modelName);
2685
- const nested = cloneModelOptionForUpdate((0, import_utils13.isPlainObject)(current[root]) ? current[root] : {});
3718
+ const directDocumentPermissions = root === "docPermissions" && current[root] && typeof current[root] === "object" && Object.hasOwn(current[root], "get");
3719
+ const nested = cloneModelOptionForUpdate(
3720
+ (0, import_utils14.isPlainObject)(current[root]) && !directDocumentPermissions ? current[root] : {}
3721
+ );
2686
3722
  if (root === "virtuals" && value === void 0) {
2687
- const parent = path.length === 1 ? nested : (0, import_utils13.get)(nested, path.slice(0, -1));
2688
- if ((0, import_utils13.isPlainObject)(parent)) delete parent[path[path.length - 1]];
2689
- } else (0, import_utils13.set)(nested, path, value);
3723
+ const parent = path.length === 1 ? nested : (0, import_utils14.get)(nested, path.slice(0, -1));
3724
+ if ((0, import_utils14.isPlainObject)(parent)) delete parent[path[path.length - 1]];
3725
+ } else (0, import_utils14.set)(nested, path, value);
2690
3726
  this.setModelOptions(modelName, { [root]: nested });
2691
3727
  }
2692
3728
  /** Frozen model/default snapshot; populate flags remain raw overrides. Read again for current values. */
@@ -2697,8 +3733,9 @@ var AccessRuntime = class {
2697
3733
  /**
2698
3734
  * Generic stored exact → parent.default → parent lookup; only undefined falls through.
2699
3735
  * The exact runtime-model-default path is the final fallback if the stored parent is
2700
- * absent. This is not the route-specific variant-to-base resolver; use
2701
- * getExactModelOption to inspect a variant including its exact model-default fallback.
3736
+ * absent. This raw generic lookup is not the final nested operation-entry resolver;
3737
+ * it may return an operation object. getExactModelOption inspects a member including
3738
+ * its same-owner exact model-default fallback, without resolving entry policy.
2702
3739
  */
2703
3740
  getModelOption(modelName, key, defaultValue) {
2704
3741
  const manager = this.getOrCreateModelOptions(modelName);
@@ -2708,7 +3745,7 @@ var AccessRuntime = class {
2708
3745
  );
2709
3746
  return getNestedOption(manager, key, defaultModelValue);
2710
3747
  }
2711
- /** Exact stored path, then the same runtime-model-default path; no parent/default or variant-to-base lookup. */
3748
+ /** Exact stored path, then the same runtime-model-default path; no parent/default or final entry resolution. */
2712
3749
  getExactModelOption(modelName, key) {
2713
3750
  const manager = this.getOrCreateModelOptions(modelName);
2714
3751
  const defaultModelValue = this.getDefaultModelOption(key);
@@ -2776,7 +3813,7 @@ var AccessRuntime = class {
2776
3813
  manager.onchange("basePath", function(newval, key, target) {
2777
3814
  target[key] = normalizeBasePath(
2778
3815
  dataName,
2779
- (0, import_utils13.isString)(newval) || (0, import_utils13.isNil)(newval) ? newval : void 0
3816
+ (0, import_utils14.isString)(newval) || (0, import_utils14.isNil)(newval) ? newval : void 0
2780
3817
  );
2781
3818
  }).build();
2782
3819
  return manager;
@@ -2790,10 +3827,30 @@ var AccessRuntime = class {
2790
3827
  return manager;
2791
3828
  }
2792
3829
  setDataOptions(dataName, options) {
3830
+ assertAuthorizationModeOptions(options, false);
3831
+ assertOperationAccessOptions(options);
3832
+ assertNoServerModelControls(
3833
+ options,
3834
+ (detail) => {
3835
+ throw new TypeError(detail);
3836
+ },
3837
+ "data-options"
3838
+ );
2793
3839
  const manager = this.getOrCreateDataOptions(dataName);
2794
3840
  manager.assign(options);
2795
3841
  }
2796
3842
  setDataOption(dataName, key, value) {
3843
+ assertAuthorizationModeKey(key, false);
3844
+ assertOperationAccessUpdate(key, value);
3845
+ const proposed = {};
3846
+ (0, import_utils14.set)(proposed, key, value);
3847
+ assertNoServerModelControls(
3848
+ proposed,
3849
+ (detail) => {
3850
+ throw new TypeError(detail);
3851
+ },
3852
+ "data-options"
3853
+ );
2797
3854
  const manager = this.getOrCreateDataOptions(dataName);
2798
3855
  manager.set(key, value);
2799
3856
  }
@@ -2836,20 +3893,20 @@ var AccessRuntime = class {
2836
3893
  const schema = model.schema;
2837
3894
  this.modelRefs[modelName] = buildRefs(schema.tree);
2838
3895
  this.modelSubs[modelName] = buildSubPaths(schema.tree);
2839
- this.modelAtts[modelName] = (0, import_utils13.keys)(schema.obj);
3896
+ this.modelAtts[modelName] = (0, import_utils14.keys)(schema.obj);
2840
3897
  }
2841
3898
  getModelRef(modelName, refPath) {
2842
3899
  this.ensureModelMeta(modelName);
2843
- const value = (0, import_utils13.get)(this.modelRefs, `${modelName}.${refPath}`, null);
2844
- return (0, import_utils13.isString)(value) ? value : null;
3900
+ const value = (0, import_utils14.get)(this.modelRefs, `${modelName}.${refPath}`, null);
3901
+ return (0, import_utils14.isString)(value) ? value : null;
2845
3902
  }
2846
3903
  getModelSub(modelName) {
2847
3904
  this.ensureModelMeta(modelName);
2848
- return (0, import_utils13.get)(this.modelSubs, modelName, []);
3905
+ return (0, import_utils14.get)(this.modelSubs, modelName, []);
2849
3906
  }
2850
3907
  getModelAtt(modelName) {
2851
3908
  this.ensureModelMeta(modelName);
2852
- return (0, import_utils13.get)(this.modelAtts, modelName, []);
3909
+ return (0, import_utils14.get)(this.modelAtts, modelName, []);
2853
3910
  }
2854
3911
  };
2855
3912
  var defaultRuntime = new AccessRuntime({ allowGlobalModelLookup: true });
@@ -2862,7 +3919,7 @@ var getGlobalOption = (key, defaultValue) => {
2862
3919
 
2863
3920
  // src/validation/common.ts
2864
3921
  var import_zod2 = require("zod");
2865
- var import_utils15 = require("@web-ts-toolkit/utils");
3922
+ var import_utils16 = require("@web-ts-toolkit/utils");
2866
3923
 
2867
3924
  // src/validation/public-admission-schema.ts
2868
3925
  var admissions = /* @__PURE__ */ new WeakMap();
@@ -2884,7 +3941,7 @@ function assertTransformedPublicAdmission(schema, value) {
2884
3941
  }
2885
3942
 
2886
3943
  // src/correlated-includes.ts
2887
- var import_utils14 = require("@web-ts-toolkit/utils");
3944
+ var import_utils15 = require("@web-ts-toolkit/utils");
2888
3945
  var PARENT_MARKER_KEY = "$parent";
2889
3946
  var ESCAPE_WRAPPER_KEY = "$escape";
2890
3947
  var SUBQUERY_PAYLOAD_KEYS = /* @__PURE__ */ new Set(["$$sq", "$$date"]);
@@ -2895,10 +3952,10 @@ var FIELD_SEGMENT_PATTERN = /^[A-Za-z_][A-Za-z0-9_$]*$/;
2895
3952
  var ARRAY_INDEX_SEGMENT_PATTERN = /^(0|[1-9]\d*)$/;
2896
3953
  var ownKeys = (value) => Object.keys(value);
2897
3954
  function isParentRefMarker(value) {
2898
- return (0, import_utils14.isPlainObject)(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === PARENT_MARKER_KEY;
3955
+ return (0, import_utils15.isPlainObject)(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === PARENT_MARKER_KEY;
2899
3956
  }
2900
3957
  function isEscapedParentRef(value) {
2901
- return (0, import_utils14.isPlainObject)(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === ESCAPE_WRAPPER_KEY;
3958
+ return (0, import_utils15.isPlainObject)(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === ESCAPE_WRAPPER_KEY;
2902
3959
  }
2903
3960
  function hasMarkerKey(value) {
2904
3961
  return ownKeys(value).includes(PARENT_MARKER_KEY) || ownKeys(value).includes(ESCAPE_WRAPPER_KEY);
@@ -2917,12 +3974,12 @@ function containsParentMarkerShape(value) {
2917
3974
  const seen = /* @__PURE__ */ new Set();
2918
3975
  const visit = (current) => {
2919
3976
  if (isParentRefMarker(current) || isEscapedParentRef(current)) return true;
2920
- if ((0, import_utils14.isArray)(current)) {
3977
+ if ((0, import_utils15.isArray)(current)) {
2921
3978
  if (seen.has(current)) return false;
2922
3979
  seen.add(current);
2923
3980
  return current.some(visit);
2924
3981
  }
2925
- if ((0, import_utils14.isPlainObject)(current)) {
3982
+ if ((0, import_utils15.isPlainObject)(current)) {
2926
3983
  if (seen.has(current)) return false;
2927
3984
  seen.add(current);
2928
3985
  if (hasMarkerKey(current)) return true;
@@ -2952,7 +4009,7 @@ function scanTemplateValueNode(value, path, issues) {
2952
4009
  }
2953
4010
  return;
2954
4011
  }
2955
- if ((0, import_utils14.isPlainObject)(value)) {
4012
+ if ((0, import_utils15.isPlainObject)(value)) {
2956
4013
  if (hasMarkerKey(value)) {
2957
4014
  issues.push({
2958
4015
  message: 'Malformed $parent reference: objects carrying $parent must be exactly { "$parent": "<field>" }',
@@ -2963,7 +4020,7 @@ function scanTemplateValueNode(value, path, issues) {
2963
4020
  scanTemplateObjectEntries(value, path, issues);
2964
4021
  return;
2965
4022
  }
2966
- if ((0, import_utils14.isArray)(value)) {
4023
+ if ((0, import_utils15.isArray)(value)) {
2967
4024
  value.forEach((item, index) => scanTemplateValueNode(item, [...path, index], issues));
2968
4025
  }
2969
4026
  }
@@ -3004,7 +4061,7 @@ function scanTemplateObjectEntries(obj, basePath, issues) {
3004
4061
  continue;
3005
4062
  }
3006
4063
  if (LOGICAL_CLAUSE_KEYS.has(key)) {
3007
- if (!(0, import_utils14.isArray)(child)) {
4064
+ if (!(0, import_utils15.isArray)(child)) {
3008
4065
  scanTemplateValueNode(child, childPath, issues);
3009
4066
  continue;
3010
4067
  }
@@ -3017,7 +4074,7 @@ function scanTemplateObjectEntries(obj, basePath, issues) {
3017
4074
  });
3018
4075
  return;
3019
4076
  }
3020
- if ((0, import_utils14.isPlainObject)(clause)) {
4077
+ if ((0, import_utils15.isPlainObject)(clause)) {
3021
4078
  scanTemplateObjectEntries(clause, clausePath, issues);
3022
4079
  }
3023
4080
  });
@@ -3028,7 +4085,7 @@ function scanTemplateObjectEntries(obj, basePath, issues) {
3028
4085
  }
3029
4086
  function validateCorrelatedFilterTemplate(filter) {
3030
4087
  const issues = [];
3031
- if (!(0, import_utils14.isPlainObject)(filter)) {
4088
+ if (!(0, import_utils15.isPlainObject)(filter)) {
3032
4089
  issues.push({ message: "Correlated include filter must be an object", path: [] });
3033
4090
  return issues;
3034
4091
  }
@@ -3156,7 +4213,7 @@ var correlatedFilterSchema = import_zod2.z.record(import_zod2.z.string(), import
3156
4213
  }
3157
4214
  });
3158
4215
  var correlatedEmptyOptionsSchema = import_zod2.z.unknown().refine(
3159
- (value) => value === void 0 || (0, import_utils15.isPlainObject)(value) && Object.keys(value).length === 0,
4216
+ (value) => value === void 0 || (0, import_utils16.isPlainObject)(value) && Object.keys(value).length === 0,
3160
4217
  "Correlated include options must be absent or empty"
3161
4218
  ).optional();
3162
4219
  var correlatedPathSchema = import_zod2.z.string().min(1).superRefine((path, ctx) => {
@@ -3193,7 +4250,7 @@ var correlatedListArgsSchema = import_zod2.z.object({
3193
4250
  include: import_zod2.z.lazy(() => correlatedNestedIncludeSchema).optional()
3194
4251
  }).strict().superRefine((args, ctx) => checkArgsMarkers(args.select, args.sort, ctx));
3195
4252
  var correlatedCountArgsSchema = import_zod2.z.unknown().refine(
3196
- (value) => value === void 0 || (0, import_utils15.isPlainObject)(value) && Object.keys(value).length === 0,
4253
+ (value) => value === void 0 || (0, import_utils16.isPlainObject)(value) && Object.keys(value).length === 0,
3197
4254
  "Count includes accept no args"
3198
4255
  ).optional();
3199
4256
  var correlatedReadByIdSchema = import_zod2.z.object({
@@ -3246,7 +4303,7 @@ var correlatedNestedIncludeSchema = import_zod2.z.union([includeItemSchema, impo
3246
4303
  var rejectDuplicateCorrelatedPaths = (items, ctx) => {
3247
4304
  const seen = /* @__PURE__ */ new Set();
3248
4305
  items.forEach((item, index) => {
3249
- if ((0, import_utils15.isPlainObject)(item) && item.mode === "correlated" && typeof item.path === "string") {
4306
+ if ((0, import_utils16.isPlainObject)(item) && item.mode === "correlated" && typeof item.path === "string") {
3250
4307
  if (seen.has(item.path)) {
3251
4308
  ctx.addIssue({
3252
4309
  code: import_zod2.z.ZodIssueCode.custom,