@web-ts-toolkit/access-router 0.58.0 → 0.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs CHANGED
@@ -29,7 +29,7 @@ function assertPublicAdmission(input, kind = "envelope") {
29
29
  for (const key of privateControls) {
30
30
  if (key in record3) {
31
31
  throw new PublicAdmissionError(
32
- `Unsupported public control ${path}.${key}; use explicit per-call internal service options for backend authorization`
32
+ key === "unsafeSkipListDocumentSnapshotChecks" || key === "unsafeSkipReadDocumentSnapshotChecks" ? `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`
33
33
  );
34
34
  }
35
35
  }
@@ -128,6 +128,8 @@ var init_public_admission = __esm({
128
128
  "skipParsing",
129
129
  "skipAuthorization",
130
130
  "alreadyAuthorized",
131
+ "unsafeSkipListDocumentSnapshotChecks",
132
+ "unsafeSkipReadDocumentSnapshotChecks",
131
133
  "operation"
132
134
  ];
133
135
  PublicAdmissionError = class extends JsonRouter.clientErrors.BadRequestError {
@@ -2833,7 +2835,9 @@ var init_runtime = __esm({
2833
2835
  queryRouteSegment: "__query",
2834
2836
  mutationRouteSegment: "__mutation",
2835
2837
  operationAccess: false,
2836
- modelPermissionPrefix: ""
2838
+ modelPermissionPrefix: "",
2839
+ unsafeSkipListDocumentSnapshotChecks: false,
2840
+ unsafeSkipReadDocumentSnapshotChecks: false
2837
2841
  }).build();
2838
2842
  this.modelOptions = {};
2839
2843
  this.modelJsonSchemas = {};
@@ -3051,11 +3055,23 @@ var init_runtime = __esm({
3051
3055
  ...defaultModelOptions,
3052
3056
  modelName
3053
3057
  });
3058
+ const snapshotFlagChanged = (newValue, key, target, oldValue) => {
3059
+ target[key] = newValue === true;
3060
+ if (newValue !== true || oldValue === true) return;
3061
+ const operation = key === "unsafeSkipReadDocumentSnapshotChecks" ? "read" : "list";
3062
+ try {
3063
+ this.getGlobalOption("logger")?.warn?.(
3064
+ `UNSAFE: ${operation} document snapshot checks disabled; source mutation can leave stale authorization decisions. Restore ${key}=false after the temporary workaround.`,
3065
+ { modelName }
3066
+ );
3067
+ } catch {
3068
+ }
3069
+ };
3054
3070
  manager.onchange("permissionSchema", function(_newval, _key, target) {
3055
3071
  refreshPermissionMetadata(target);
3056
3072
  }).onchange("modelPermissionPrefix", function(_newval, _key, target) {
3057
3073
  refreshPermissionMetadata(target);
3058
- }).onchange("basePath", function(newval, key, target) {
3074
+ }).onchange("unsafeSkipListDocumentSnapshotChecks", snapshotFlagChanged).onchange("unsafeSkipReadDocumentSnapshotChecks", snapshotFlagChanged).onchange("basePath", function(newval, key, target) {
3059
3075
  target[key] = normalizeBasePath(
3060
3076
  modelName,
3061
3077
  isString4(newval) || isNil2(newval) ? newval : void 0
@@ -3724,6 +3740,9 @@ function resolveServiceAuthorization(input) {
3724
3740
  );
3725
3741
  for (const value of Object.values(permissions)) if (value && typeof value === "object") Object.freeze(value);
3726
3742
  Object.freeze(permissions);
3743
+ const readAccess = outputAccess.rowAccess;
3744
+ const readResponse = input.readResponse === true && (input.applicability ?? "service") === "service" && scopePath.length === 0 && outputAccess.operation === "read" && (readAccess === "read" || readAccess === "list") && outputAccess.outputAccess === readAccess && outputAccess.virtualAccess === readAccess && outputAccess.docPermissionsAccess === readAccess && (input.parent === void 0 || callRecord(input.parent).readResponse);
3745
+ if (readResponse && input.parent) assertAuthorizationBinding(input.parent, input.binding);
3727
3746
  const call = Object.freeze(/* @__PURE__ */ Object.create(null));
3728
3747
  calls.set(call, {
3729
3748
  binding: Object.freeze({ ...input.binding, scopePath: Object.freeze(scopePath) }),
@@ -3734,7 +3753,9 @@ function resolveServiceAuthorization(input) {
3734
3753
  // normalizeFields constructs only mode strings and validated string paths.
3735
3754
  output: Object.freeze({ access: outputAccess, catalog, outputFields: policy.outputFields }),
3736
3755
  permissions,
3737
- provenance: input.parent ? callRecord(input.parent).provenance : call
3756
+ provenance: input.parent ? callRecord(input.parent).provenance : call,
3757
+ readResponse,
3758
+ validateDocumentSnapshots: !(input.listResponse === true && input.parent === void 0 && (input.applicability ?? "service") === "service" && outputAccess.operation === "list" && outputAccess.rowAccess === "list" && outputAccess.outputAccess === "list" && scopePath.length === 0 && configuration.unsafeSkipListDocumentSnapshotChecks === true || readResponse && configuration.unsafeSkipReadDocumentSnapshotChecks === true)
3738
3759
  });
3739
3760
  return call;
3740
3761
  }
@@ -3755,6 +3776,10 @@ function readServiceAuthorizationAccess(call, binding) {
3755
3776
  assertAuthorizationBinding(call, binding);
3756
3777
  return callRecord(call).output.access;
3757
3778
  }
3779
+ function requiresDocumentSnapshotChecks(call, binding) {
3780
+ assertAuthorizationBinding(call, binding);
3781
+ return callRecord(call).validateDocumentSnapshots;
3782
+ }
3758
3783
  function readServiceAuthorizationHydration(call, binding) {
3759
3784
  assertAuthorizationBinding(call, binding);
3760
3785
  return copyAuthorizationValue({ hydration: callRecord(call).configuration.hydration }, true);
@@ -3801,11 +3826,10 @@ function readServiceOutputPolicy(call, binding) {
3801
3826
  function readServiceOutputFieldAuthorization(call, binding) {
3802
3827
  assertAuthorizationBinding(call, binding);
3803
3828
  const record3 = callRecord(call);
3804
- const reusable = record3.reusableFieldConfiguration ??= hasStableConfigurationCopies(record3.configuration.permissionSchema) && // Coercion methods can observe an object's identity even without native
3805
- // leaves. Keep those receivers local to the original resolution boundary.
3806
- (record3.configuration.modelPermissionPrefix === null || typeof record3.configuration.modelPermissionPrefix !== "object");
3829
+ const reusable = reusableOutputFieldConfiguration(record3);
3807
3830
  return Object.freeze({
3808
3831
  access: record3.output.access,
3832
+ catalog: record3.output.catalog,
3809
3833
  outputFields: record3.output.outputFields,
3810
3834
  reusable,
3811
3835
  ...copyAuthorizationValue(
@@ -3817,6 +3841,16 @@ function readServiceOutputFieldAuthorization(call, binding) {
3817
3841
  )
3818
3842
  });
3819
3843
  }
3844
+ function reusableOutputFieldConfiguration(record3) {
3845
+ return record3.reusableFieldConfiguration ??= hasStableConfigurationCopies(record3.configuration.permissionSchema) && // Coercion methods can observe an object's identity even without native
3846
+ // leaves. Keep those receivers local to the original resolution boundary.
3847
+ (record3.configuration.modelPermissionPrefix === null || typeof record3.configuration.modelPermissionPrefix !== "object");
3848
+ }
3849
+ function canPrepareStaticOutputPolicy(call, binding) {
3850
+ assertAuthorizationBinding(call, binding);
3851
+ const record3 = callRecord(call);
3852
+ return reusableOutputFieldConfiguration(record3) && typeof (record3.configuration.modelPermissionPrefix ?? "") === "string";
3853
+ }
3820
3854
  function getAuthorizationPermissions(call, binding) {
3821
3855
  assertAuthorizationBinding(call, binding);
3822
3856
  return callRecord(call).permissions;
@@ -3835,435 +3869,98 @@ var init_service_authorization = __esm({
3835
3869
  }
3836
3870
  });
3837
3871
 
3838
- // src/acl/document-authorization.ts
3839
- import { Document as Document3 } from "mongoose";
3840
- function normalizeOutputAuthorizationOptions(input, options, purpose) {
3841
- const value = authorizationRecord(options, "output options");
3842
- for (const key of Reflect.ownKeys(value)) {
3843
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
3844
- if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable) {
3845
- authorizationError("invalid output option property");
3846
- }
3847
- }
3848
- assertAuthorizationKeys(
3849
- value,
3850
- ["authorization", "scopePath", "documentAuthorization", ...purpose ? ["purpose"] : []],
3851
- "output options"
3852
- );
3853
- if (purpose && value.purpose !== purpose) authorizationError("genAllowedFields requires purpose: output");
3854
- if (Object.prototype.hasOwnProperty.call(value, "documentAuthorization")) {
3855
- if (Object.prototype.hasOwnProperty.call(value, "authorization") || Object.prototype.hasOwnProperty.call(value, "scopePath")) {
3856
- authorizationError("document handle cannot be mixed with raw policy/scope");
3857
- }
3858
- const handle = value.documentAuthorization;
3859
- const stage = stageRecord(documentRecord(handle).stage);
3860
- const binding = Object.freeze({ ...input.binding, scopePath: stage.binding.scopePath });
3861
- assertAuthorizationBinding(stage.call, binding);
3862
- const access = readServiceAuthorizationAccess(stage.call, binding);
3863
- if (input.access.outputAccess !== access.outputAccess) authorizationError("document access mismatch");
3864
- return Object.freeze({ kind: "document", documentAuthorization: handle, binding });
3865
- }
3866
- if (value.scopePath !== void 0 && !Array.isArray(value.scopePath))
3867
- authorizationError("scopePath must be an array");
3868
- return Object.freeze({
3869
- kind: "policy",
3870
- authorization: resolveServiceAuthorization({
3871
- ...input,
3872
- binding: {
3873
- ...input.binding,
3874
- scopePath: copyAuthorizationValue(value.scopePath)
3875
- },
3876
- authorization: value.authorization,
3877
- applicability: "output"
3878
- })
3879
- });
3872
+ // src/acl/field-authorization.ts
3873
+ function extractScopedOutputRule(schema, field, access) {
3874
+ if (!schema || !Object.prototype.hasOwnProperty.call(schema, field)) return void 0;
3875
+ const raw = schema[field];
3876
+ return raw && typeof raw === "object" && !Array.isArray(raw) && Object.prototype.hasOwnProperty.call(raw, access) ? raw[access] : raw;
3880
3877
  }
3881
- function stageRecord(stage) {
3882
- const record3 = stages.get(stage);
3883
- if (!record3) authorizationError("invalid document stage");
3884
- if (!matchesAuthorizationSnapshot(record3.input, record3.snapshot)) authorizationError("changed document snapshot");
3885
- return record3;
3878
+ function extractOutputFieldRules(schema, path, access) {
3879
+ return extractOutputFieldRuleEntries(schema, path, access).map((entry) => entry.rule);
3886
3880
  }
3887
- function documentRecord(handle) {
3888
- const record3 = documents.get(handle);
3889
- if (!record3) authorizationError("invalid document handle");
3890
- stageRecord(record3.stage);
3891
- return record3;
3881
+ function extractOutputFieldRuleEntries(schema, path, access, prefix = "") {
3882
+ if (!schema) return [{ path: `${prefix}${path}`, rule: void 0 }];
3883
+ if (Object.prototype.hasOwnProperty.call(schema, path))
3884
+ return [{ path: `${prefix}${path}`, rule: extractScopedOutputRule(schema, path, access) }];
3885
+ const [head, ...rest] = path.split(".");
3886
+ const rule = extractScopedOutputRule(schema, head, access);
3887
+ const raw = schema[head];
3888
+ const entry = { path: `${prefix}${head}`, rule };
3889
+ if (!rest.length || !raw?.sub) return [entry];
3890
+ return [entry, ...extractOutputFieldRuleEntries(raw.sub, rest.join("."), access, `${prefix}${head}.`)];
3892
3891
  }
3893
- function createDocumentAuthorizationStage(call, binding, projectedSnapshot) {
3894
- assertAuthorizationBinding(call, binding);
3895
- authorizationRecord(projectedSnapshot, "projected document snapshot");
3896
- const stage = Object.freeze(/* @__PURE__ */ Object.create(null));
3897
- stages.set(stage, {
3898
- call,
3899
- binding: Object.freeze({ ...binding, scopePath: Object.freeze([...binding.scopePath ?? []]) }),
3900
- input: projectedSnapshot,
3901
- snapshot: copyAuthorizationValue(projectedSnapshot, "document")
3902
- });
3903
- return stage;
3892
+ function hasExplicitFieldGrant(policy, path) {
3893
+ return policy?.mode === "unrestricted" || policy?.mode === "grant" && policy.paths.some((grant) => path === grant || path.startsWith(`${grant}.`));
3904
3894
  }
3905
- function assertDocumentAuthorizationStage(stage, call, binding, projectedSnapshot) {
3906
- const record3 = stageRecord(stage);
3907
- assertAuthorizationBinding(record3.call, binding);
3908
- if (record3.call !== call || record3.input !== projectedSnapshot || !matchesAuthorizationSnapshot(projectedSnapshot, record3.snapshot)) {
3909
- authorizationError("document call/stage/snapshot mismatch");
3910
- }
3895
+ function classifyRequestFieldRule(rule, permissions, modelPermissionPrefix = "") {
3896
+ if (typeof rule === "boolean") return rule ? "granted" : "denied";
3897
+ if (typeof rule === "function") return "deferred";
3898
+ const validator = createValidator((key) => permissions.has(key));
3899
+ if (typeof rule !== "string" && !Array.isArray(rule)) return "denied";
3900
+ if (typeof rule === "string" ? validator.stringHandler(rule) : validator.arrayHandler(rule)) return "granted";
3901
+ const possible = createValidator(
3902
+ (key) => permissions.has(key) || !modelPermissionPrefix || key.startsWith(modelPermissionPrefix)
3903
+ );
3904
+ return (typeof rule === "string" ? possible.stringHandler(rule) : possible.arrayHandler(rule)) ? "deferred" : "denied";
3911
3905
  }
3912
- function resolveDocumentAuthorization(stage, resolveGrants) {
3913
- const record3 = stageRecord(stage);
3914
- if (!record3.result) {
3915
- record3.result = Promise.resolve().then(async () => {
3916
- stageRecord(stage);
3917
- const result2 = resolveGrants.call(
3918
- record3.binding.request,
3919
- copyAuthorizationValue(record3.snapshot, "document"),
3920
- getAuthorizationPermissions(record3.call, record3.binding)
3921
- );
3922
- const grants = result2 && typeof result2.then === "function" ? await result2 : result2;
3923
- stageRecord(stage);
3924
- const ownedGrants = copyAuthorizationValue(authorizationRecord(grants, "document grants"));
3925
- const handle = Object.freeze(/* @__PURE__ */ Object.create(null));
3926
- documents.set(handle, { stage, grants: ownedGrants, decisions: /* @__PURE__ */ new Map() });
3927
- return handle;
3928
- });
3929
- }
3930
- return record3.result;
3906
+ function prepareRequestFieldRule(rule, permissions, modelPermissionPrefix = "") {
3907
+ const state = classifyRequestFieldRule(rule, permissions, modelPermissionPrefix);
3908
+ const invariant = state === "denied" && modelPermissionPrefix ? classifyRequestFieldRule(rule, permissions) : state;
3909
+ return Object.freeze({ state, decision: invariant === "deferred" ? void 0 : invariant === "granted" });
3931
3910
  }
3932
- function readDocumentAuthorization(handle, binding) {
3933
- const record3 = documentRecord(handle);
3934
- const stage = stageRecord(record3.stage);
3935
- assertAuthorizationBinding(stage.call, binding);
3936
- return Object.freeze({
3937
- authorization: stage.call,
3938
- stage: record3.stage,
3939
- grants: copyAuthorizationValue(record3.grants),
3940
- ...readServiceAuthorizationAccess(stage.call, binding)
3941
- });
3911
+ function combineFieldAuthorizationStates(states2) {
3912
+ return states2.includes("denied") ? "denied" : states2.includes("deferred") ? "deferred" : "granted";
3942
3913
  }
3943
- function readDocumentAuthorizationAccess(handle, binding) {
3944
- const record3 = documentRecord(handle);
3945
- const stage = stageRecord(record3.stage);
3946
- return Object.freeze({
3947
- authorization: stage.call,
3948
- stage: record3.stage,
3949
- ...readServiceAuthorizationAccess(stage.call, binding)
3950
- });
3914
+ function classifyEffectiveFieldAuthorization(args) {
3915
+ if (hasExplicitFieldGrant(args.outputFields, args.path)) return "granted";
3916
+ const states2 = args.rules.map(
3917
+ (rule) => classifyRequestFieldRule(rule, args.globalPermissions, args.modelPermissionPrefix)
3918
+ );
3919
+ return combineFieldAuthorizationStates(states2);
3951
3920
  }
3952
- function memoizeDocumentFieldDecision(handle, binding, field, evaluate) {
3953
- const record3 = documentRecord(handle);
3954
- const stage = stageRecord(record3.stage);
3955
- assertAuthorizationBinding(stage.call, binding);
3956
- let decision = record3.decisions.get(field);
3957
- if (decision) {
3958
- return decision.then((result2) => {
3959
- stageRecord(record3.stage);
3960
- assertAuthorizationBinding(stage.call, binding);
3961
- return result2;
3962
- });
3963
- } else {
3964
- decision = Promise.resolve().then(async () => {
3965
- stageRecord(record3.stage);
3966
- assertAuthorizationBinding(stage.call, binding);
3967
- const result2 = await evaluate.call(
3968
- stage.binding.request,
3969
- getAuthorizationPermissions(stage.call, binding),
3970
- copyAuthorizationValue(record3.grants)
3971
- );
3972
- stageRecord(record3.stage);
3973
- assertAuthorizationBinding(stage.call, binding);
3974
- if (typeof result2 !== "boolean") authorizationError("field decision must be boolean");
3975
- return result2;
3976
- });
3977
- record3.decisions.set(field, decision);
3921
+ async function evaluateScopedAccessRule(args) {
3922
+ const { req, rule, globalPermissions, docPermissions, modelPermissionPrefix } = args;
3923
+ if (typeof rule === "boolean") return rule;
3924
+ const validator = createValidator((key) => {
3925
+ try {
3926
+ if (globalPermissions?.has(key)) return true;
3927
+ } catch {
3928
+ }
3929
+ try {
3930
+ return Boolean((docPermissions ?? {})[stripModelPermissionPrefix(key, modelPermissionPrefix)]);
3931
+ } catch {
3932
+ return false;
3933
+ }
3934
+ });
3935
+ if (typeof rule === "string") return validator.stringHandler(rule);
3936
+ if (Array.isArray(rule)) return validator.arrayHandler(rule);
3937
+ if (typeof rule === "function") {
3938
+ try {
3939
+ return Boolean(await rule.call(req, globalPermissions, docPermissions));
3940
+ } catch {
3941
+ return false;
3942
+ }
3978
3943
  }
3979
- return decision;
3980
- }
3981
- function unchangedOutput(output, record3) {
3982
- if (!matchesAuthorizationSnapshot(output, record3.snapshot)) return false;
3983
- const identities = outputIdentities(output);
3984
- return identities.length === record3.identities.length && identities.every((identity, i) => identity === record3.identities[i]);
3944
+ return false;
3985
3945
  }
3986
- function assertDocumentAuthorization(handle, use) {
3987
- const record3 = documentRecord(handle);
3988
- const stage = stageRecord(record3.stage);
3989
- assertAuthorizationBinding(stage.call, use.binding);
3990
- if (use.authorization !== void 0 && stage.call !== use.authorization || use.stage !== void 0 && record3.stage !== use.stage || readServiceAuthorizationAccess(stage.call, use.binding).outputAccess !== use.outputAccess) {
3991
- authorizationError("document call/access/stage mismatch");
3992
- }
3993
- const association = outputs.get(use.output);
3994
- if (!association || association.handle !== handle || !unchangedOutput(use.output, association)) {
3995
- authorizationError("unknown, replaced or mutated authorized output");
3946
+ async function evaluateEffectiveFieldAuthorization(args) {
3947
+ if (hasExplicitFieldGrant(args.outputFields, args.path)) return true;
3948
+ for (const [index, rule] of args.rules.entries()) {
3949
+ if (!await (args.evaluateRule ? args.evaluateRule(rule, index) : evaluateScopedAccessRule({ ...args, rule })))
3950
+ return false;
3996
3951
  }
3952
+ return true;
3997
3953
  }
3998
- function associateDocumentAuthorization(handle, binding, output) {
3999
- const record3 = documentRecord(handle);
4000
- assertAuthorizationBinding(stageRecord(record3.stage).call, binding);
4001
- if (!output || typeof output !== "object") authorizationError("output must be an object");
4002
- if (outputs.has(output)) {
4003
- const previous = outputs.get(output);
4004
- if (previous.handle !== handle || !unchangedOutput(output, previous))
4005
- authorizationError("output already associated");
4006
- return;
4007
- }
4008
- outputs.set(output, {
4009
- handle,
4010
- snapshot: copyAuthorizationValue(output, "document"),
4011
- identities: outputIdentities(output)
4012
- });
4013
- }
4014
- function transferDocumentAuthorization(handle, use, copy) {
4015
- assertDocumentAuthorization(handle, use);
4016
- associateDocumentAuthorization(handle, use.binding, copy);
4017
- }
4018
- function isKnownAuthorizationOutput(output) {
4019
- return outputs.has(output);
4020
- }
4021
- function getAssociatedDocumentAuthorization(output, call) {
4022
- const record3 = outputs.get(output);
4023
- if (!record3 || !unchangedOutput(output, record3)) return void 0;
4024
- const stage = stageRecord(documentRecord(record3.handle).stage);
4025
- if (call && getAuthorizationProvenance(stage.call) !== getAuthorizationProvenance(call)) return void 0;
4026
- return record3.handle;
4027
- }
4028
- function transferDocumentAuthorizationGraph(source, copy, copyOrigins) {
4029
- const seen = /* @__PURE__ */ new WeakSet();
4030
- const visit = (source2, copy2) => {
4031
- if (!copy2 || typeof copy2 !== "object" || seen.has(copy2)) return;
4032
- seen.add(copy2);
4033
- source2 = copyOrigins?.get(copy2) ?? source2;
4034
- if (source2 instanceof Document3) source2 = source2._doc;
4035
- const original = source2 && typeof source2 === "object" ? source2 : void 0;
4036
- if (!original && !copyOrigins) return;
4037
- const association = original && outputs.get(original);
4038
- if (association) {
4039
- const stage = stageRecord(documentRecord(association.handle).stage);
4040
- transferDocumentAuthorization(
4041
- association.handle,
4042
- {
4043
- binding: stage.binding,
4044
- output: original,
4045
- outputAccess: readServiceAuthorizationAccess(stage.call, stage.binding).outputAccess,
4046
- authorization: stage.call,
4047
- stage: documentRecord(association.handle).stage
4048
- },
4049
- copy2
4050
- );
4051
- }
4052
- for (const key of Object.keys(copy2)) {
4053
- const descriptor = original && Object.getOwnPropertyDescriptor(original, key);
4054
- if (descriptor && "value" in descriptor) {
4055
- visit(descriptor.value, copy2[key]);
4056
- } else if (copyOrigins) {
4057
- visit(void 0, copy2[key]);
4058
- }
4059
- }
4060
- };
4061
- visit(source, copy);
4062
- }
4063
- function createServiceOutputContext(diagnostic, handle, use) {
4064
- assertDocumentAuthorization(handle, use);
4065
- const rootOutput = use.output;
4066
- const root = outputs.get(rootOutput);
4067
- const graph = new Set(root.identities);
4068
- const call = stageRecord(documentRecord(handle).stage).call;
4069
- const context = { ...diagnostic };
4070
- Object.defineProperties(context, {
4071
- documentAuthorization: { value: handle, enumerable: false, writable: false, configurable: false },
4072
- getDocumentAuthorization: {
4073
- enumerable: false,
4074
- writable: false,
4075
- configurable: false,
4076
- value(output) {
4077
- if (!graph.has(output) || !unchangedOutput(rootOutput, root)) return void 0;
4078
- const association = outputs.get(output);
4079
- if (!association || !unchangedOutput(output, association)) return void 0;
4080
- try {
4081
- documentRecord(handle);
4082
- const child = stageRecord(documentRecord(association.handle).stage);
4083
- if (getAuthorizationProvenance(child.call) !== getAuthorizationProvenance(call)) return void 0;
4084
- return association.handle;
4085
- } catch {
4086
- return void 0;
4087
- }
4088
- }
4089
- }
4090
- });
4091
- return context;
4092
- }
4093
- var stages, documents, outputs;
4094
- var init_document_authorization = __esm({
4095
- "src/acl/document-authorization.ts"() {
4096
- init_service_authorization();
4097
- init_authorization_snapshot();
4098
- stages = /* @__PURE__ */ new WeakMap();
4099
- documents = /* @__PURE__ */ new WeakMap();
4100
- outputs = /* @__PURE__ */ new WeakMap();
4101
- }
4102
- });
4103
-
4104
- // src/output/include-output.ts
4105
- import { set as set5 } from "@web-ts-toolkit/utils";
4106
- function prepareIncludeOutput(doc) {
4107
- if (stateFor(doc)) return doc;
4108
- const source = isolateDocForOutput(doc);
4109
- transferDocumentAuthorizationGraph(doc, source);
4110
- const working = deepIsolateValue(source);
4111
- outputs2.set(working, { original: doc, source, attachments: [] });
4112
- return working;
4113
- }
4114
- function attachIncludeOutput(doc, path, value) {
4115
- const state = stateFor(doc);
4116
- if (!state) throw new Error("Include attachment requires a prepared output row");
4117
- state.attachments.push({ path, value });
4118
- set5(doc, path, deepIsolateValue(value));
4119
- }
4120
- function getIncludeSource(doc) {
4121
- return stateFor(doc)?.source ?? doc;
4122
- }
4123
- function getIncludeOriginal(doc) {
4124
- return stateFor(doc)?.original ?? doc;
4125
- }
4126
- function restoreIncludeOutput(doc, output) {
4127
- const attachments = stateFor(doc)?.attachments;
4128
- if (!attachments?.length) return void 0;
4129
- const origins = /* @__PURE__ */ new WeakMap();
4130
- for (const { path, value } of attachments) {
4131
- const copy = deepIsolateValue(value);
4132
- if (copy !== null && typeof copy === "object") origins.set(copy, value);
4133
- set5(output, path, copy);
4134
- }
4135
- return origins;
4136
- }
4137
- var outputs2, stateFor;
4138
- var init_include_output = __esm({
4139
- "src/output/include-output.ts"() {
4140
- init_document_authorization();
4141
- init_document();
4142
- outputs2 = /* @__PURE__ */ new WeakMap();
4143
- stateFor = (doc) => doc !== null && typeof doc === "object" ? outputs2.get(doc) : void 0;
4144
- }
4145
- });
4146
-
4147
- // src/helpers/request-work.ts
4148
- function getRequestWorkState(req, runtime) {
4149
- let owners = states.get(req);
4150
- if (!owners) {
4151
- owners = /* @__PURE__ */ new WeakMap();
4152
- states.set(req, owners);
4153
- }
4154
- let state = owners.get(runtime);
4155
- if (!state) {
4156
- const limits = resolveRequestComplexity(runtime.getGlobalOption("requestComplexity"));
4157
- state = {
4158
- totalQueries: 0,
4159
- scheduler: new RequestConcurrencyScheduler(limits.maxBulkConcurrency),
4160
- hookGate: new SharedHookGate(limits.maxHookConcurrency)
4161
- };
4162
- owners.set(runtime, state);
4163
- }
4164
- return state;
4165
- }
4166
- var states;
4167
- var init_request_work = __esm({
4168
- "src/helpers/request-work.ts"() {
4169
- init_request_complexity();
4170
- init_concurrency();
4171
- states = /* @__PURE__ */ new WeakMap();
4172
- }
4173
- });
4174
-
4175
- // src/acl/field-authorization.ts
4176
- function extractScopedOutputRule(schema, field, access) {
4177
- if (!schema || !Object.prototype.hasOwnProperty.call(schema, field)) return void 0;
4178
- const raw = schema[field];
4179
- return raw && typeof raw === "object" && !Array.isArray(raw) && Object.prototype.hasOwnProperty.call(raw, access) ? raw[access] : raw;
4180
- }
4181
- function extractOutputFieldRules(schema, path, access) {
4182
- return extractOutputFieldRuleEntries(schema, path, access).map((entry) => entry.rule);
4183
- }
4184
- function extractOutputFieldRuleEntries(schema, path, access, prefix = "") {
4185
- if (!schema) return [{ path: `${prefix}${path}`, rule: void 0 }];
4186
- if (Object.prototype.hasOwnProperty.call(schema, path))
4187
- return [{ path: `${prefix}${path}`, rule: extractScopedOutputRule(schema, path, access) }];
4188
- const [head, ...rest] = path.split(".");
4189
- const rule = extractScopedOutputRule(schema, head, access);
4190
- const raw = schema[head];
4191
- const entry = { path: `${prefix}${head}`, rule };
4192
- if (!rest.length || !raw?.sub) return [entry];
4193
- return [entry, ...extractOutputFieldRuleEntries(raw.sub, rest.join("."), access, `${prefix}${head}.`)];
4194
- }
4195
- function hasExplicitFieldGrant(policy, path) {
4196
- return policy?.mode === "unrestricted" || policy?.mode === "grant" && policy.paths.some((grant) => path === grant || path.startsWith(`${grant}.`));
4197
- }
4198
- function classifyRequestFieldRule(rule, permissions, modelPermissionPrefix = "") {
4199
- if (typeof rule === "boolean") return rule ? "granted" : "denied";
4200
- if (typeof rule === "function") return "deferred";
4201
- const validator = createValidator((key) => permissions.has(key));
4202
- if (typeof rule !== "string" && !Array.isArray(rule)) return "denied";
4203
- if (typeof rule === "string" ? validator.stringHandler(rule) : validator.arrayHandler(rule)) return "granted";
4204
- const possible = createValidator(
4205
- (key) => permissions.has(key) || !modelPermissionPrefix || key.startsWith(modelPermissionPrefix)
4206
- );
4207
- return (typeof rule === "string" ? possible.stringHandler(rule) : possible.arrayHandler(rule)) ? "deferred" : "denied";
4208
- }
4209
- function prepareRequestFieldRule(rule, permissions, modelPermissionPrefix = "") {
4210
- const state = classifyRequestFieldRule(rule, permissions, modelPermissionPrefix);
4211
- const invariant = state === "denied" && modelPermissionPrefix ? classifyRequestFieldRule(rule, permissions) : state;
4212
- return Object.freeze({ state, decision: invariant === "deferred" ? void 0 : invariant === "granted" });
4213
- }
4214
- function combineFieldAuthorizationStates(states2) {
4215
- return states2.includes("denied") ? "denied" : states2.includes("deferred") ? "deferred" : "granted";
4216
- }
4217
- function classifyEffectiveFieldAuthorization(args) {
4218
- if (hasExplicitFieldGrant(args.outputFields, args.path)) return "granted";
4219
- const states2 = args.rules.map(
4220
- (rule) => classifyRequestFieldRule(rule, args.globalPermissions, args.modelPermissionPrefix)
4221
- );
4222
- return combineFieldAuthorizationStates(states2);
4223
- }
4224
- async function evaluateScopedAccessRule(args) {
4225
- const { req, rule, globalPermissions, docPermissions, modelPermissionPrefix } = args;
4226
- if (typeof rule === "boolean") return rule;
4227
- const validator = createValidator((key) => {
4228
- try {
4229
- if (globalPermissions?.has(key)) return true;
4230
- } catch {
4231
- }
4232
- try {
4233
- return Boolean((docPermissions ?? {})[stripModelPermissionPrefix(key, modelPermissionPrefix)]);
4234
- } catch {
4235
- return false;
4236
- }
4237
- });
4238
- if (typeof rule === "string") return validator.stringHandler(rule);
4239
- if (Array.isArray(rule)) return validator.arrayHandler(rule);
4240
- if (typeof rule === "function") {
4241
- try {
4242
- return Boolean(await rule.call(req, globalPermissions, docPermissions));
4243
- } catch {
4244
- return false;
4245
- }
4246
- }
4247
- return false;
4248
- }
4249
- async function evaluateEffectiveFieldAuthorization(args) {
4250
- if (hasExplicitFieldGrant(args.outputFields, args.path)) return true;
4251
- for (const [index, rule] of args.rules.entries()) {
4252
- if (!await (args.evaluateRule ? args.evaluateRule(rule, index) : evaluateScopedAccessRule({ ...args, rule })))
4253
- return false;
4254
- }
4255
- return true;
4256
- }
4257
- var stripModelPermissionPrefix;
4258
- var init_field_authorization = __esm({
4259
- "src/acl/field-authorization.ts"() {
4260
- init_helpers();
4261
- stripModelPermissionPrefix = (key, prefix) => prefix && key.startsWith(prefix) ? key.slice(prefix.length) : key;
3954
+ var stripModelPermissionPrefix;
3955
+ var init_field_authorization = __esm({
3956
+ "src/acl/field-authorization.ts"() {
3957
+ init_helpers();
3958
+ stripModelPermissionPrefix = (key, prefix) => prefix && key.startsWith(prefix) ? key.slice(prefix.length) : key;
4262
3959
  }
4263
3960
  });
4264
3961
 
4265
3962
  // src/acl/virtual-projection.ts
4266
- import { get as get6, isArray as isArray7, isPlainObject as isPlainObject16 } from "@web-ts-toolkit/utils";
3963
+ import { get as get6, isArray as isArray6, isPlainObject as isPlainObject15 } from "@web-ts-toolkit/utils";
4267
3964
  function planVirtualProjection(args) {
4268
3965
  if (args.snapshot.catalog) return planCatalogProjection(args);
4269
3966
  const {
@@ -4497,20 +4194,20 @@ var init_virtual_projection = __esm({
4497
4194
  init_virtual_populate_dependencies();
4498
4195
  init_virtual_descriptor();
4499
4196
  getScopedPermissionSchema = (root, scopePath) => {
4500
- if (!root || !isPlainObject16(root)) return null;
4197
+ if (!root || !isPlainObject15(root)) return null;
4501
4198
  if (scopePath.length === 0) return root;
4502
4199
  const scoped = get6(root, scopePath.join("."));
4503
- return isPlainObject16(scoped) ? scoped : null;
4200
+ return isPlainObject15(scoped) ? scoped : null;
4504
4201
  };
4505
4202
  resolveAlwaysSelectForAccess = (raw, access) => {
4506
4203
  if (!raw) return [];
4507
- if (isArray7(raw)) return [...raw];
4508
- if (isPlainObject16(raw)) {
4204
+ if (isArray6(raw)) return [...raw];
4205
+ if (isPlainObject15(raw)) {
4509
4206
  const record3 = raw;
4510
4207
  const exact = record3[access];
4511
- if (isArray7(exact)) return [...exact];
4208
+ if (isArray6(exact)) return [...exact];
4512
4209
  const def = record3.default;
4513
- if (isArray7(def)) return [...def];
4210
+ if (isArray6(def)) return [...def];
4514
4211
  return [];
4515
4212
  }
4516
4213
  return [];
@@ -4535,6 +4232,35 @@ var init_virtual_projection = __esm({
4535
4232
  });
4536
4233
 
4537
4234
  // src/acl/output-projection.ts
4235
+ import { types as types2 } from "util";
4236
+ function copyOutputDecisionFields(value) {
4237
+ if (!Array.isArray(value) || types2.isProxy(value) || Object.getPrototypeOf(value) !== Array.prototype) return;
4238
+ const length = Object.getOwnPropertyDescriptor(value, "length").value;
4239
+ if (length > 2e4) return;
4240
+ const fields = [];
4241
+ for (let index = 0; index < length; index++) {
4242
+ const slot = Object.getOwnPropertyDescriptor(value, String(index));
4243
+ if (!slot || !("value" in slot) || typeof slot.value !== "string") return;
4244
+ fields.push(slot.value);
4245
+ }
4246
+ return Object.freeze(fields);
4247
+ }
4248
+ function readStaticOutputPlanFields(plan, authorization) {
4249
+ const record3 = staticPlanFields.get(plan);
4250
+ if (!record3 || record3.authorization !== authorization || types2.isProxy(plan)) return;
4251
+ const ownValue2 = (key) => {
4252
+ const slot = Object.getOwnPropertyDescriptor(plan, key);
4253
+ return slot && "value" in slot ? slot.value : void 0;
4254
+ };
4255
+ if (ownValue2("authorization") !== authorization || ownValue2("authorizationBinding") !== record3.binding) return;
4256
+ const children = ownValue2("childPlans");
4257
+ if (children !== record3.children || types2.isProxy(children) || Reflect.ownKeys(children).length) return;
4258
+ const persisted = copyOutputDecisionFields(ownValue2("outputPersistedFields"));
4259
+ const virtuals = copyOutputDecisionFields(ownValue2("outputVirtualNames"));
4260
+ const same = (a, b) => a?.length === b.length && a.every((field, index) => field === b[index]);
4261
+ if (!same(persisted, record3.persisted) || !same(virtuals, record3.virtuals)) return;
4262
+ return Object.freeze([.../* @__PURE__ */ new Set([...record3.persisted, ...record3.virtuals])]);
4263
+ }
4538
4264
  function compactPersistedProjection(paths) {
4539
4265
  const unique = [...new Set(paths.filter((p) => p && !p.startsWith("-")))];
4540
4266
  return unique.filter((path) => !unique.some((parent) => parent !== path && path.startsWith(`${parent}.`)));
@@ -4563,6 +4289,13 @@ function planAuthorizedModelProjection(args) {
4563
4289
  );
4564
4290
  plan.authorization = args.authorization;
4565
4291
  plan.authorizationBinding = Object.freeze({ ...args.binding, scopePath: Object.freeze(scope2) });
4292
+ staticPlanFields.set(plan, {
4293
+ authorization: args.authorization,
4294
+ binding: plan.authorizationBinding,
4295
+ persisted: Object.freeze([...plan.outputPersistedFields]),
4296
+ virtuals: Object.freeze([...plan.outputVirtualNames]),
4297
+ children: plan.childPlans
4298
+ });
4566
4299
  return plan;
4567
4300
  }
4568
4301
  function planCatalogProjection(args, outputFields = { mode: "request" }) {
@@ -4660,116 +4393,757 @@ function planCatalogProjection(args, outputFields = { mode: "request" }) {
4660
4393
  outputAccess
4661
4394
  });
4662
4395
  }
4663
- const ancestors = /* @__PURE__ */ new Set();
4664
- for (const path of [...persisted, ...allVirtuals]) {
4665
- const parts = path.split(".");
4666
- for (let i = 1; i < parts.length; i++) ancestors.add(parts.slice(0, i).join("."));
4396
+ const ancestors = /* @__PURE__ */ new Set();
4397
+ for (const path of [...persisted, ...allVirtuals]) {
4398
+ const parts = path.split(".");
4399
+ for (let i = 1; i < parts.length; i++) ancestors.add(parts.slice(0, i).join("."));
4400
+ }
4401
+ const children = {};
4402
+ for (const name of [...ancestors].filter((p) => !p.includes("."))) {
4403
+ const childIncludes = includes.filter((p) => p.startsWith(`${name}.`)).map((p) => p.slice(name.length + 1));
4404
+ const childExcludes = excludes.filter((p) => p.startsWith(`${name}.`)).map((p) => `-${p.slice(name.length + 1)}`);
4405
+ const childSelect = mode === "include" && !includes.includes(name) ? [...childIncludes, ...childExcludes] : childExcludes;
4406
+ children[name] = planCatalogProjection(
4407
+ {
4408
+ ...args,
4409
+ scopePath: [...args.scopePath ?? [], name, "sub"],
4410
+ requestedSelect: childSelect,
4411
+ effectiveSelect: childSelect,
4412
+ related: [],
4413
+ internalFetch: { baseFields: [] }
4414
+ },
4415
+ outputFields
4416
+ );
4417
+ }
4418
+ const internal = args.internalFetch ?? {};
4419
+ const fetchIdRetained = scope2.length === 0 || catalog.paths.includes(full("_id")) || !!catalog.dynamicPaths?.some((p) => p.endsWith("._id") && matchesCatalogPattern(p, full("_id")));
4420
+ const identity = fetchIdRetained ? ["_id"] : [];
4421
+ const always = scope2.length ? [] : [
4422
+ .../* @__PURE__ */ new Set([
4423
+ ...resolveAlwaysSelectForAccess(snapshot.alwaysSelectFields, outputAccess),
4424
+ ...resolveAlwaysSelectForAccess(snapshot.alwaysSelectFields, docPermissionsAccess)
4425
+ ])
4426
+ ];
4427
+ const joins = [...internal.joinFields ?? [], ...internal.extraPersistedFields ?? []];
4428
+ const forced = [...always, ...joins, ...internal.baseFields ?? identity, ...internal.identityFields ?? []];
4429
+ const fetchSafe = (path) => isSafeOutputPath(path) && !virtual(full(path));
4430
+ const dependencies = Object.keys(depProvenance).filter(fetchSafe);
4431
+ const childFetch = Object.entries(children).flatMap(([name, child]) => {
4432
+ if (child.persistedFetchSelection.length) return child.persistedFetchSelection.map((p) => `${name}.${p}`);
4433
+ depProvenance[name] = allVirtuals.filter((p) => p.startsWith(`${name}.`));
4434
+ return [name];
4435
+ });
4436
+ const publicChildFetch = Object.entries(children).flatMap(
4437
+ ([name, child]) => child.publicPersistedFetchSelection.length ? child.publicPersistedFetchSelection.map((path) => `${name}.${path}`) : [name]
4438
+ );
4439
+ const publicPersistedFetchSelection = compactPersistedProjection([
4440
+ ...persisted,
4441
+ ...dependencies,
4442
+ ...forced.filter(fetchSafe),
4443
+ ...identity,
4444
+ ...publicChildFetch
4445
+ ]);
4446
+ const publicStructurePaths = Object.entries(children).flatMap(([name, child]) => {
4447
+ if ([...persisted, ...dependencies, ...forced].some((path) => name === path || name.startsWith(`${path}.`)))
4448
+ return [];
4449
+ return child.publicPersistedFetchSelection.length ? (child.publicStructurePaths ?? []).map((path) => `${name}.${path}`) : [name];
4450
+ });
4451
+ const populateRefs = candidates.flatMap((candidate) => candidate.populateDependencies.map((dep) => dep.path));
4452
+ const privateFields = [...dependencies, ...populateRefs, ...forced.filter(fetchSafe), ...identity, ...childFetch];
4453
+ const fetch = compactPersistedProjection([...persisted, ...privateFields]);
4454
+ const outputIdExcluded = excludes.includes("_id");
4455
+ const coveredOutput = (path) => persisted.some((p) => p === path || path.startsWith(`${p}.`));
4456
+ const outputPersisted = [.../* @__PURE__ */ new Set([...persisted.filter((p) => !p.includes(".")), ...Object.keys(children)])];
4457
+ return {
4458
+ receivingModelName,
4459
+ scopePath: [...args.scopePath ?? []],
4460
+ responseScopePath: Object.freeze(scope2),
4461
+ virtualAccess,
4462
+ outputAccess,
4463
+ docPermissionsAccess,
4464
+ selectionMode: mode,
4465
+ effectiveSelectNorm: normalized,
4466
+ outputPersistedFields: outputPersisted,
4467
+ outputVirtualNames: candidates.map((c) => c.name),
4468
+ outputSelection: [...outputPersisted, ...candidates.map((c) => c.name), ...outputIdExcluded ? ["-_id"] : []],
4469
+ fieldStates: Object.freeze(states2),
4470
+ minimalAncestorPaths: Object.freeze([...ancestors]),
4471
+ persistedFetchSelection: fetch,
4472
+ publicPersistedFetchSelection,
4473
+ publicStructurePaths,
4474
+ candidates,
4475
+ depProvenance,
4476
+ virtualOnlyDeps: Object.keys(depProvenance).filter((p) => fetchSafe(p) && !coveredOutput(p)),
4477
+ internalOnlyFields: [
4478
+ ...new Set(privateFields.filter((p) => !coveredOutput(p) && (p !== "_id" || outputIdExcluded)))
4479
+ ],
4480
+ outputIdExcluded,
4481
+ fetchIdRetained,
4482
+ internalIdentityFields: identity,
4483
+ internalJoinFields: [...new Set(joins)],
4484
+ childPlans: children,
4485
+ // A parent never supplies its authority to a target; related execution will
4486
+ // call planAuthorizedModelProjection with the independently derived owner.
4487
+ relatedPlans: (args.related ?? []).map(
4488
+ (rel) => planVirtualProjection({
4489
+ ...rel,
4490
+ receivingModelName: rel.targetModelName,
4491
+ snapshot: rel.targetSnapshot,
4492
+ globalPermissions
4493
+ })
4494
+ )
4495
+ };
4496
+ }
4497
+ var staticPlanFields;
4498
+ var init_output_projection = __esm({
4499
+ "src/acl/output-projection.ts"() {
4500
+ init_query();
4501
+ init_authorization_snapshot();
4502
+ init_field_catalog();
4503
+ init_field_authorization();
4504
+ init_virtual_populate_dependencies();
4505
+ init_service_authorization();
4506
+ init_virtual_projection();
4507
+ staticPlanFields = /* @__PURE__ */ new WeakMap();
4508
+ }
4509
+ });
4510
+
4511
+ // src/acl/output-field-policy.ts
4512
+ import { types as types3 } from "util";
4513
+ import { isPlainObject as isPlainObject16 } from "@web-ts-toolkit/utils";
4514
+ function callFieldPolicy(authorization, binding) {
4515
+ assertAuthorizationBinding(authorization, binding);
4516
+ let policy = fieldPolicies.get(authorization);
4517
+ if (!policy) {
4518
+ const view = readServiceOutputFieldAuthorization(authorization, binding);
4519
+ policy = {
4520
+ schema: view.permissionSchema,
4521
+ requestPaths: view.permissionSchema == null || isPlainObject16(view.permissionSchema) && Object.isFrozen(view.permissionSchema) ? Object.freeze(Object.keys(view.permissionSchema ?? {})) : void 0,
4522
+ prefix: view.modelPermissionPrefix ?? "",
4523
+ outputFields: view.outputFields,
4524
+ catalog: view.catalog,
4525
+ reusable: view.reusable,
4526
+ accesses: /* @__PURE__ */ new Map()
4527
+ };
4528
+ if (view.reusable) fieldPolicies.set(authorization, policy);
4529
+ }
4530
+ return policy;
4531
+ }
4532
+ function requestRuleClassification(entry, authorization, permissions, prefix) {
4533
+ if (typeof prefix !== "string") return void 0;
4534
+ let classification = entry.classifications.get(authorization);
4535
+ if (!classification) {
4536
+ classification = prepareRequestFieldRule(entry.rule, permissions, prefix);
4537
+ entry.classifications.set(authorization, classification);
4538
+ }
4539
+ return classification;
4540
+ }
4541
+ function invariantRuleLookup(schema, path) {
4542
+ if (schema == null) return true;
4543
+ if (!isPlainObject16(schema) || !Object.isFrozen(schema)) return false;
4544
+ const exact = Object.getOwnPropertyDescriptor(schema, path);
4545
+ if (exact) {
4546
+ const raw2 = exact.value;
4547
+ return !raw2 || typeof raw2 !== "object" || Array.isArray(raw2) || isPlainObject16(raw2) && Object.isFrozen(raw2);
4548
+ }
4549
+ const [head, ...rest] = path.split(".");
4550
+ const raw = Object.getOwnPropertyDescriptor(schema, head)?.value;
4551
+ if (raw == null) return true;
4552
+ if (!isPlainObject16(raw) || !Object.isFrozen(raw)) return false;
4553
+ const sub = Object.getOwnPropertyDescriptor(raw, "sub");
4554
+ return !rest.length || !sub || invariantRuleLookup(sub.value, rest.join("."));
4555
+ }
4556
+ function prepareOutputPath(policy, authorization, binding, path, access) {
4557
+ let cache = policy.accesses.get(access);
4558
+ if (!cache) {
4559
+ cache = /* @__PURE__ */ new Map();
4560
+ policy.accesses.set(access, cache);
4561
+ }
4562
+ let prepared = cache.get(path);
4563
+ if (!prepared) {
4564
+ const invariant = invariantRuleLookup(policy.schema, path);
4565
+ const permissions = getAuthorizationPermissions(authorization, binding);
4566
+ const entries = extractOutputFieldRuleEntries(policy.schema, path, access).map((entry) => ({
4567
+ ...entry,
4568
+ classifications: /* @__PURE__ */ new WeakMap()
4569
+ }));
4570
+ const classifications = entries.map(
4571
+ (entry) => requestRuleClassification(entry, authorization, permissions, policy.prefix)
4572
+ );
4573
+ const backendGrant = hasExplicitFieldGrant(policy.outputFields, path);
4574
+ prepared = {
4575
+ entries,
4576
+ backendGrant,
4577
+ state: backendGrant ? "granted" : classifications.every((value) => value !== void 0) ? combineFieldAuthorizationStates(classifications.map((value) => value.state)) : void 0
4578
+ };
4579
+ if (invariant) cache.set(path, prepared);
4580
+ }
4581
+ return prepared;
4582
+ }
4583
+ function ordinaryContainer(value) {
4584
+ return value !== null && typeof value === "object" && !types3.isProxy(value) && Object.getPrototypeOf(value) === Object.prototype && Object.isFrozen(value);
4585
+ }
4586
+ function booleanRuleLookup(schema, path, access) {
4587
+ if (schema == null) return true;
4588
+ if (!ordinaryContainer(schema)) return false;
4589
+ const booleanRule = (raw) => {
4590
+ if (typeof raw === "boolean" || raw === void 0) return true;
4591
+ if (!ordinaryContainer(raw)) return false;
4592
+ const slot2 = Object.getOwnPropertyDescriptor(raw, access);
4593
+ return !!slot2 && "value" in slot2 && (typeof slot2.value === "boolean" || slot2.value === void 0);
4594
+ };
4595
+ const exact = Object.getOwnPropertyDescriptor(schema, path);
4596
+ if (exact) return "value" in exact && booleanRule(exact.value);
4597
+ const [head, ...rest] = path.split(".");
4598
+ const slot = Object.getOwnPropertyDescriptor(schema, head);
4599
+ if (!slot) return !(head in schema);
4600
+ if (!("value" in slot) || !booleanRule(slot.value)) return false;
4601
+ if (!rest.length || slot.value == null) return true;
4602
+ if (!ordinaryContainer(slot.value)) return false;
4603
+ const sub = Object.getOwnPropertyDescriptor(slot.value, "sub");
4604
+ if (!sub) return !("sub" in slot.value);
4605
+ if (!("value" in sub)) return false;
4606
+ return !sub.value || booleanRuleLookup(sub.value, rest.join("."), access);
4607
+ }
4608
+ function staticFieldPolicy(authorization, binding) {
4609
+ return canPrepareStaticOutputPolicy(authorization, binding) ? callFieldPolicy(authorization, binding) : void 0;
4610
+ }
4611
+ function prepareStaticOutputPaths(authorization, binding, paths, access, requestOnly = false) {
4612
+ const policy = staticFieldPolicy(authorization, binding);
4613
+ if (!policy?.reusable || typeof policy.prefix !== "string") return void 0;
4614
+ const { catalog } = policy;
4615
+ if (paths.some(
4616
+ (path) => !requestOnly && !isCatalogOutputPath(catalog, path) || !booleanRuleLookup(policy.schema, path, access)
4617
+ ))
4618
+ return void 0;
4619
+ return paths.map((path) => {
4620
+ const prepared = prepareOutputPath(policy, authorization, binding, path, access);
4621
+ return {
4622
+ path,
4623
+ backendGrant: !requestOnly && prepared.backendGrant,
4624
+ granted: prepared.backendGrant || prepared.entries.every((entry) => entry.rule === true),
4625
+ entries: prepared.entries.map((entry) => ({
4626
+ key: `request:${access}:${entry.path}`,
4627
+ allowed: entry.rule === true
4628
+ }))
4629
+ };
4630
+ });
4631
+ }
4632
+ var fieldPolicies;
4633
+ var init_output_field_policy = __esm({
4634
+ "src/acl/output-field-policy.ts"() {
4635
+ init_service_authorization();
4636
+ init_field_authorization();
4637
+ init_field_catalog();
4638
+ fieldPolicies = /* @__PURE__ */ new WeakMap();
4639
+ }
4640
+ });
4641
+
4642
+ // src/acl/document-authorization.ts
4643
+ import { types as types4 } from "util";
4644
+ import { Document as Document3 } from "mongoose";
4645
+ function bindOutputDocumentOwner(handle, knownOutput, owner, binding) {
4646
+ lookupDocumentOwner(handle);
4647
+ if (knownOutput || owner && unresolvedDocuments.has(owner)) unresolvedDocuments.add(handle);
4648
+ if (owner) {
4649
+ lookupDocumentOwner(owner);
4650
+ owningDocuments.set(handle, { handle: owner, binding });
4651
+ }
4652
+ }
4653
+ function readOutputDocumentOwner(handle) {
4654
+ return owningDocuments.get(handle);
4655
+ }
4656
+ function isUnresolvedOutputDocument(handle) {
4657
+ return unresolvedDocuments.has(handle);
4658
+ }
4659
+ function normalizeOutputAuthorizationOptions(input, options, purpose) {
4660
+ const value = authorizationRecord(options, "output options");
4661
+ for (const key of Reflect.ownKeys(value)) {
4662
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
4663
+ if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable) {
4664
+ authorizationError("invalid output option property");
4665
+ }
4666
+ }
4667
+ assertAuthorizationKeys(
4668
+ value,
4669
+ ["authorization", "scopePath", "documentAuthorization", ...purpose ? ["purpose"] : []],
4670
+ "output options"
4671
+ );
4672
+ if (purpose && value.purpose !== purpose) authorizationError("genAllowedFields requires purpose: output");
4673
+ if (Object.prototype.hasOwnProperty.call(value, "documentAuthorization")) {
4674
+ if (Object.prototype.hasOwnProperty.call(value, "authorization") || Object.prototype.hasOwnProperty.call(value, "scopePath")) {
4675
+ authorizationError("document handle cannot be mixed with raw policy/scope");
4676
+ }
4677
+ const handle = value.documentAuthorization;
4678
+ const { stage } = validateDocumentOwner(handle);
4679
+ const binding = Object.freeze({ ...input.binding, scopePath: stage.binding.scopePath });
4680
+ assertAuthorizationBinding(stage.call, binding);
4681
+ const access = readServiceAuthorizationAccess(stage.call, binding);
4682
+ if (input.access.outputAccess !== access.outputAccess) authorizationError("document access mismatch");
4683
+ return Object.freeze({ kind: "document", documentAuthorization: handle, binding });
4684
+ }
4685
+ if (value.scopePath !== void 0 && !Array.isArray(value.scopePath))
4686
+ authorizationError("scopePath must be an array");
4687
+ return Object.freeze({
4688
+ kind: "policy",
4689
+ authorization: resolveServiceAuthorization({
4690
+ ...input,
4691
+ binding: {
4692
+ ...input.binding,
4693
+ scopePath: copyAuthorizationValue(value.scopePath)
4694
+ },
4695
+ authorization: value.authorization,
4696
+ applicability: "output"
4697
+ })
4698
+ });
4699
+ }
4700
+ function lookupStageOwner(stage) {
4701
+ const record3 = stages.get(stage);
4702
+ if (!record3) authorizationError("invalid document stage");
4703
+ return record3;
4704
+ }
4705
+ function lookupDocumentOwner(handle) {
4706
+ const record3 = documents.get(handle);
4707
+ if (!record3) authorizationError("invalid document handle");
4708
+ return record3;
4709
+ }
4710
+ function validateStageOwner(record3) {
4711
+ if (!record3.validateSnapshot) return;
4712
+ if (!matchesAuthorizationSnapshot(record3.input, record3.snapshot)) authorizationError("changed document snapshot");
4713
+ }
4714
+ function validateDocumentOwner(handle) {
4715
+ const document = lookupDocumentOwner(handle);
4716
+ const stage = lookupStageOwner(document.stage);
4717
+ validateStageOwner(stage);
4718
+ validateStageOwner(stage);
4719
+ return { document, stage };
4720
+ }
4721
+ function createDocumentAuthorizationStage(call, binding, projectedSnapshot) {
4722
+ assertAuthorizationBinding(call, binding);
4723
+ authorizationRecord(projectedSnapshot, "projected document snapshot");
4724
+ const stage = Object.freeze(/* @__PURE__ */ Object.create(null));
4725
+ const ownedBinding = Object.freeze({ ...binding, scopePath: Object.freeze([...binding.scopePath ?? []]) });
4726
+ const snapshot = copyAuthorizationValue(projectedSnapshot, "document");
4727
+ stages.set(stage, {
4728
+ call,
4729
+ binding: ownedBinding,
4730
+ input: projectedSnapshot,
4731
+ snapshot,
4732
+ validateSnapshot: requiresDocumentSnapshotChecks(call, binding)
4733
+ });
4734
+ return stage;
4735
+ }
4736
+ function assertDocumentAuthorizationStage(stage, call, binding, projectedSnapshot) {
4737
+ const record3 = lookupStageOwner(stage);
4738
+ validateStageOwner(record3);
4739
+ assertAuthorizationBinding(record3.call, binding);
4740
+ if (record3.call !== call || record3.input !== projectedSnapshot || record3.validateSnapshot && !matchesAuthorizationSnapshot(projectedSnapshot, record3.snapshot)) {
4741
+ authorizationError("document call/stage/snapshot mismatch");
4742
+ }
4743
+ }
4744
+ function resolveDocumentAuthorization(stage, resolveGrants) {
4745
+ const record3 = lookupStageOwner(stage);
4746
+ validateStageOwner(record3);
4747
+ if (!record3.result) {
4748
+ record3.result = Promise.resolve().then(async () => {
4749
+ validateStageOwner(record3);
4750
+ const result2 = resolveGrants.call(
4751
+ record3.binding.request,
4752
+ copyAuthorizationValue(record3.snapshot, "document"),
4753
+ getAuthorizationPermissions(record3.call, record3.binding)
4754
+ );
4755
+ const grants = result2 && typeof result2.then === "function" ? await result2 : result2;
4756
+ validateStageOwner(record3);
4757
+ const ownedGrants = copyAuthorizationValue(authorizationRecord(grants, "document grants"));
4758
+ const handle = Object.freeze(/* @__PURE__ */ Object.create(null));
4759
+ documents.set(handle, { stage, grants: ownedGrants, decisions: /* @__PURE__ */ new Map() });
4760
+ return handle;
4761
+ });
4762
+ }
4763
+ return record3.result;
4764
+ }
4765
+ function readDocumentAuthorization(handle, binding) {
4766
+ const { document: record3, stage } = validateDocumentOwner(handle);
4767
+ assertAuthorizationBinding(stage.call, binding);
4768
+ return Object.freeze({
4769
+ authorization: stage.call,
4770
+ stage: record3.stage,
4771
+ grants: copyAuthorizationValue(record3.grants),
4772
+ ...readServiceAuthorizationAccess(stage.call, binding)
4773
+ });
4774
+ }
4775
+ function readDocumentAuthorizationAccess(handle, binding) {
4776
+ const { document: record3, stage } = validateDocumentOwner(handle);
4777
+ return Object.freeze({
4778
+ authorization: stage.call,
4779
+ stage: record3.stage,
4780
+ ...readServiceAuthorizationAccess(stage.call, binding)
4781
+ });
4782
+ }
4783
+ function memoizeDocumentFieldDecision(handle, binding, field, evaluate) {
4784
+ const { document: record3, stage } = validateDocumentOwner(handle);
4785
+ assertAuthorizationBinding(stage.call, binding);
4786
+ let decision = record3.decisions.get(field);
4787
+ if (decision) {
4788
+ return decision.promise.then((result2) => {
4789
+ validateStageOwner(stage);
4790
+ assertAuthorizationBinding(stage.call, binding);
4791
+ return result2;
4792
+ });
4793
+ } else {
4794
+ const created = {
4795
+ state: "pending",
4796
+ promise: Promise.resolve().then(async () => {
4797
+ validateStageOwner(stage);
4798
+ assertAuthorizationBinding(stage.call, binding);
4799
+ const result2 = await evaluate.call(
4800
+ stage.binding.request,
4801
+ getAuthorizationPermissions(stage.call, binding),
4802
+ copyAuthorizationValue(record3.grants)
4803
+ );
4804
+ validateStageOwner(stage);
4805
+ assertAuthorizationBinding(stage.call, binding);
4806
+ if (typeof result2 !== "boolean") authorizationError("field decision must be boolean");
4807
+ return result2;
4808
+ })
4809
+ };
4810
+ void created.promise.then(
4811
+ (value) => {
4812
+ created.value = value;
4813
+ created.state = "fulfilled";
4814
+ },
4815
+ () => {
4816
+ created.state = "rejected";
4817
+ }
4818
+ );
4819
+ decision = created;
4820
+ record3.decisions.set(field, decision);
4821
+ }
4822
+ return decision.promise;
4823
+ }
4824
+ function ordinaryDecisionBinding(binding) {
4825
+ if (types4.isProxy(binding) || Object.getPrototypeOf(binding) !== Object.prototype) return false;
4826
+ for (const key of ["request", "runtime", "model", "modelName", "scopePath"]) {
4827
+ const slot = Object.getOwnPropertyDescriptor(binding, key);
4828
+ if (slot && !("value" in slot)) return false;
4829
+ if (!slot && key !== "scopePath") return false;
4830
+ if (!slot && key in binding) return false;
4831
+ }
4832
+ const scope2 = Object.getOwnPropertyDescriptor(binding, "scopePath")?.value;
4833
+ return scope2 === void 0 || copyOutputDecisionFields(scope2) !== void 0;
4834
+ }
4835
+ function settleStaticFieldBatch(handle, binding, paths) {
4836
+ const { document, stage } = validateDocumentOwner(handle);
4837
+ if (!ordinaryDecisionBinding(binding)) {
4838
+ validateDocumentOwner(handle);
4839
+ return;
4840
+ }
4841
+ assertAuthorizationBinding(stage.call, binding);
4842
+ const expected = /* @__PURE__ */ new Map();
4843
+ const journal = /* @__PURE__ */ new Map();
4844
+ const result2 = /* @__PURE__ */ new Map();
4845
+ const unresolved = unresolvedDocuments.has(handle);
4846
+ let available = !owningDocuments.has(handle);
4847
+ const read = (key) => {
4848
+ const memo = document.decisions.get(key);
4849
+ expected.set(key, memo);
4850
+ if (memo) {
4851
+ if (memo.state !== "fulfilled") available = false;
4852
+ return memo.value;
4853
+ }
4854
+ return journal.get(key);
4855
+ };
4856
+ for (const path of paths) {
4857
+ if (!available) break;
4858
+ let allowed = path.outputKey ? read(path.outputKey) : void 0;
4859
+ if (!available) break;
4860
+ if (allowed === void 0) {
4861
+ const policy = path.policy;
4862
+ if (!policy) {
4863
+ available = false;
4864
+ break;
4865
+ }
4866
+ if (path.outputKey && unresolved && !policy.granted) allowed = false;
4867
+ else if (path.outputKey && policy.backendGrant) allowed = true;
4868
+ else {
4869
+ allowed = true;
4870
+ for (const entry of policy.entries) {
4871
+ let decision = read(entry.key);
4872
+ if (!available) break;
4873
+ if (decision === void 0) {
4874
+ decision = entry.allowed;
4875
+ journal.set(entry.key, decision);
4876
+ }
4877
+ if (!decision) {
4878
+ allowed = false;
4879
+ break;
4880
+ }
4881
+ }
4882
+ }
4883
+ if (!available) break;
4884
+ if (path.outputKey) journal.set(path.outputKey, allowed);
4885
+ }
4886
+ result2.set(path.field, allowed);
4887
+ }
4888
+ validateDocumentOwner(handle);
4889
+ if (!ordinaryDecisionBinding(binding)) return;
4890
+ assertAuthorizationBinding(stage.call, binding);
4891
+ if (!available || owningDocuments.has(handle) || unresolvedDocuments.has(handle) !== unresolved || [...expected].some(([key, memo]) => document.decisions.get(key) !== memo))
4892
+ return;
4893
+ for (const [key, value] of journal) {
4894
+ document.decisions.set(key, { promise: Promise.resolve(value), state: "fulfilled", value });
4895
+ }
4896
+ return result2;
4897
+ }
4898
+ function tryStaticOutputFieldDecisions(handle, binding, plan, fields) {
4899
+ const document = lookupDocumentOwner(handle);
4900
+ const stage = lookupStageOwner(document.stage);
4901
+ if (!ordinaryDecisionBinding(binding) || owningDocuments.has(handle)) return;
4902
+ assertAuthorizationBinding(stage.call, binding);
4903
+ const canonical = readStaticOutputPlanFields(plan, stage.call);
4904
+ const ownedFields = copyOutputDecisionFields(fields);
4905
+ if (!canonical || !ownedFields) return;
4906
+ let index = 0;
4907
+ for (const field of ownedFields) {
4908
+ const next = canonical.indexOf(field, index);
4909
+ if (next < 0) return;
4910
+ index = next + 1;
4911
+ }
4912
+ const prefix = (binding.scopePath ?? []).join(".");
4913
+ const paths = ownedFields.map((field) => {
4914
+ const path = prefix ? `${prefix}.${field}` : field;
4915
+ return { field, path, outputKey: `output:${path}` };
4916
+ });
4917
+ const missing = [];
4918
+ for (const path of paths) {
4919
+ const memo = document.decisions.get(path.outputKey);
4920
+ if (memo && memo.state !== "fulfilled") return;
4921
+ if (!memo) missing.push(path.path);
4922
+ }
4923
+ const access = readServiceAuthorizationAccess(stage.call, binding).outputAccess;
4924
+ const prepared = missing.length ? prepareStaticOutputPaths(stage.call, binding, missing, access) : [];
4925
+ if (!prepared) return;
4926
+ const policies = new Map(prepared.map((policy) => [policy.path, policy]));
4927
+ const decisions = settleStaticFieldBatch(
4928
+ handle,
4929
+ binding,
4930
+ paths.map((path) => ({ ...path, policy: policies.get(path.path) }))
4931
+ );
4932
+ if (decisions && !readStaticOutputPlanFields(plan, stage.call)) authorizationError("changed static output plan");
4933
+ return decisions;
4934
+ }
4935
+ function tryStaticRequestFieldPaths(handle, binding, access) {
4936
+ const document = lookupDocumentOwner(handle);
4937
+ const stage = lookupStageOwner(document.stage);
4938
+ if (!ordinaryDecisionBinding(binding) || owningDocuments.has(handle) || typeof access !== "string") return;
4939
+ const policy = staticFieldPolicy(stage.call, binding);
4940
+ if (!policy?.reusable || !policy.requestPaths) return;
4941
+ const prepared = prepareStaticOutputPaths(stage.call, binding, policy.requestPaths, access, true);
4942
+ if (!prepared) return;
4943
+ const decisions = settleStaticFieldBatch(
4944
+ handle,
4945
+ binding,
4946
+ prepared.map((policy2) => ({ field: policy2.path, policy: policy2 }))
4947
+ );
4948
+ return decisions && [...decisions].filter(([, allowed]) => allowed).map(([field]) => field);
4949
+ }
4950
+ function unchangedOutput(output, record3) {
4951
+ if (!matchesAuthorizationSnapshot(output, record3.snapshot)) return false;
4952
+ const identities = outputIdentities(output);
4953
+ return identities.length === record3.identities.length && identities.every((identity, i) => identity === record3.identities[i]);
4954
+ }
4955
+ function assertDocumentAuthorization(handle, use) {
4956
+ const { document: record3, stage } = validateDocumentOwner(handle);
4957
+ assertAuthorizationBinding(stage.call, use.binding);
4958
+ if (use.authorization !== void 0 && stage.call !== use.authorization || use.stage !== void 0 && record3.stage !== use.stage || readServiceAuthorizationAccess(stage.call, use.binding).outputAccess !== use.outputAccess) {
4959
+ authorizationError("document call/access/stage mismatch");
4960
+ }
4961
+ const association = outputs.get(use.output);
4962
+ if (!association || association.handle !== handle || !unchangedOutput(use.output, association)) {
4963
+ authorizationError("unknown, replaced or mutated authorized output");
4964
+ }
4965
+ }
4966
+ function associateDocumentAuthorization(handle, binding, output) {
4967
+ const { stage } = validateDocumentOwner(handle);
4968
+ assertAuthorizationBinding(stage.call, binding);
4969
+ if (!output || typeof output !== "object") authorizationError("output must be an object");
4970
+ if (outputs.has(output)) {
4971
+ const previous = outputs.get(output);
4972
+ if (previous.handle !== handle || !unchangedOutput(output, previous))
4973
+ authorizationError("output already associated");
4974
+ return;
4975
+ }
4976
+ outputs.set(output, {
4977
+ handle,
4978
+ snapshot: copyAuthorizationValue(output, "document"),
4979
+ identities: outputIdentities(output)
4980
+ });
4981
+ }
4982
+ function transferDocumentAuthorization(handle, use, copy) {
4983
+ assertDocumentAuthorization(handle, use);
4984
+ associateDocumentAuthorization(handle, use.binding, copy);
4985
+ }
4986
+ function isKnownAuthorizationOutput(output) {
4987
+ return outputs.has(output);
4988
+ }
4989
+ function getAssociatedDocumentAuthorization(output, call) {
4990
+ const record3 = outputs.get(output);
4991
+ if (!record3 || !unchangedOutput(output, record3)) return void 0;
4992
+ const { stage } = validateDocumentOwner(record3.handle);
4993
+ if (call && getAuthorizationProvenance(stage.call) !== getAuthorizationProvenance(call)) return void 0;
4994
+ return record3.handle;
4995
+ }
4996
+ function transferDocumentAuthorizationGraph(source, copy, copyOrigins) {
4997
+ const seen = /* @__PURE__ */ new WeakSet();
4998
+ const visit = (source2, copy2) => {
4999
+ if (!copy2 || typeof copy2 !== "object" || seen.has(copy2)) return;
5000
+ seen.add(copy2);
5001
+ source2 = copyOrigins?.get(copy2) ?? source2;
5002
+ if (source2 instanceof Document3) source2 = source2._doc;
5003
+ const original = source2 && typeof source2 === "object" ? source2 : void 0;
5004
+ if (!original && !copyOrigins) return;
5005
+ const association = original && outputs.get(original);
5006
+ if (association) {
5007
+ const { document, stage } = validateDocumentOwner(association.handle);
5008
+ const outputAccess = readServiceAuthorizationAccess(stage.call, stage.binding).outputAccess;
5009
+ validateStageOwner(stage);
5010
+ transferDocumentAuthorization(
5011
+ association.handle,
5012
+ {
5013
+ binding: stage.binding,
5014
+ output: original,
5015
+ outputAccess,
5016
+ authorization: stage.call,
5017
+ stage: document.stage
5018
+ },
5019
+ copy2
5020
+ );
5021
+ }
5022
+ for (const key of Object.keys(copy2)) {
5023
+ const descriptor = original && Object.getOwnPropertyDescriptor(original, key);
5024
+ if (descriptor && "value" in descriptor) {
5025
+ visit(descriptor.value, copy2[key]);
5026
+ } else if (copyOrigins) {
5027
+ visit(void 0, copy2[key]);
5028
+ }
5029
+ }
5030
+ };
5031
+ visit(source, copy);
5032
+ }
5033
+ function createServiceOutputContext(diagnostic, handle, use) {
5034
+ assertDocumentAuthorization(handle, use);
5035
+ const rootOutput = use.output;
5036
+ const root = outputs.get(rootOutput);
5037
+ const graph = new Set(root.identities);
5038
+ const { stage } = validateDocumentOwner(handle);
5039
+ const call = stage.call;
5040
+ const context = { ...diagnostic };
5041
+ Object.defineProperties(context, {
5042
+ documentAuthorization: { value: handle, enumerable: false, writable: false, configurable: false },
5043
+ getDocumentAuthorization: {
5044
+ enumerable: false,
5045
+ writable: false,
5046
+ configurable: false,
5047
+ value(output) {
5048
+ if (!graph.has(output) || !unchangedOutput(rootOutput, root)) return void 0;
5049
+ const association = outputs.get(output);
5050
+ if (!association || !unchangedOutput(output, association)) return void 0;
5051
+ try {
5052
+ validateStageOwner(lookupStageOwner(lookupDocumentOwner(handle).stage));
5053
+ const { stage: child } = validateDocumentOwner(association.handle);
5054
+ if (getAuthorizationProvenance(child.call) !== getAuthorizationProvenance(call)) return void 0;
5055
+ return association.handle;
5056
+ } catch {
5057
+ return void 0;
5058
+ }
5059
+ }
5060
+ }
5061
+ });
5062
+ return context;
5063
+ }
5064
+ var stages, documents, outputs, unresolvedDocuments, owningDocuments;
5065
+ var init_document_authorization = __esm({
5066
+ "src/acl/document-authorization.ts"() {
5067
+ init_service_authorization();
5068
+ init_authorization_snapshot();
5069
+ init_output_projection();
5070
+ init_output_field_policy();
5071
+ stages = /* @__PURE__ */ new WeakMap();
5072
+ documents = /* @__PURE__ */ new WeakMap();
5073
+ outputs = /* @__PURE__ */ new WeakMap();
5074
+ unresolvedDocuments = /* @__PURE__ */ new WeakSet();
5075
+ owningDocuments = /* @__PURE__ */ new WeakMap();
5076
+ }
5077
+ });
5078
+
5079
+ // src/output/include-output.ts
5080
+ import { set as set5 } from "@web-ts-toolkit/utils";
5081
+ function prepareIncludeOutput(doc) {
5082
+ if (stateFor(doc)) return doc;
5083
+ const source = isolateDocForOutput(doc);
5084
+ transferDocumentAuthorizationGraph(doc, source);
5085
+ const working = deepIsolateValue(source);
5086
+ outputs2.set(working, { original: doc, source, attachments: [] });
5087
+ return working;
5088
+ }
5089
+ function attachIncludeOutput(doc, path, value) {
5090
+ const state = stateFor(doc);
5091
+ if (!state) throw new Error("Include attachment requires a prepared output row");
5092
+ state.attachments.push({ path, value });
5093
+ set5(doc, path, deepIsolateValue(value));
5094
+ }
5095
+ function getIncludeSource(doc) {
5096
+ return stateFor(doc)?.source ?? doc;
5097
+ }
5098
+ function getIncludeOriginal(doc) {
5099
+ return stateFor(doc)?.original ?? doc;
5100
+ }
5101
+ function restoreIncludeOutput(doc, output) {
5102
+ const attachments = stateFor(doc)?.attachments;
5103
+ if (!attachments?.length) return void 0;
5104
+ const origins = /* @__PURE__ */ new WeakMap();
5105
+ for (const { path, value } of attachments) {
5106
+ const copy = deepIsolateValue(value);
5107
+ if (copy !== null && typeof copy === "object") origins.set(copy, value);
5108
+ set5(output, path, copy);
5109
+ }
5110
+ return origins;
5111
+ }
5112
+ var outputs2, stateFor;
5113
+ var init_include_output = __esm({
5114
+ "src/output/include-output.ts"() {
5115
+ init_document_authorization();
5116
+ init_document();
5117
+ outputs2 = /* @__PURE__ */ new WeakMap();
5118
+ stateFor = (doc) => doc !== null && typeof doc === "object" ? outputs2.get(doc) : void 0;
4667
5119
  }
4668
- const children = {};
4669
- for (const name of [...ancestors].filter((p) => !p.includes("."))) {
4670
- const childIncludes = includes.filter((p) => p.startsWith(`${name}.`)).map((p) => p.slice(name.length + 1));
4671
- const childExcludes = excludes.filter((p) => p.startsWith(`${name}.`)).map((p) => `-${p.slice(name.length + 1)}`);
4672
- const childSelect = mode === "include" && !includes.includes(name) ? [...childIncludes, ...childExcludes] : childExcludes;
4673
- children[name] = planCatalogProjection(
4674
- {
4675
- ...args,
4676
- scopePath: [...args.scopePath ?? [], name, "sub"],
4677
- requestedSelect: childSelect,
4678
- effectiveSelect: childSelect,
4679
- related: [],
4680
- internalFetch: { baseFields: [] }
4681
- },
4682
- outputFields
4683
- );
5120
+ });
5121
+
5122
+ // src/helpers/request-work.ts
5123
+ function getRequestWorkState(req, runtime) {
5124
+ let owners = states.get(req);
5125
+ if (!owners) {
5126
+ owners = /* @__PURE__ */ new WeakMap();
5127
+ states.set(req, owners);
4684
5128
  }
4685
- const internal = args.internalFetch ?? {};
4686
- const fetchIdRetained = scope2.length === 0 || catalog.paths.includes(full("_id")) || !!catalog.dynamicPaths?.some((p) => p.endsWith("._id") && matchesCatalogPattern(p, full("_id")));
4687
- const identity = fetchIdRetained ? ["_id"] : [];
4688
- const always = scope2.length ? [] : [
4689
- .../* @__PURE__ */ new Set([
4690
- ...resolveAlwaysSelectForAccess(snapshot.alwaysSelectFields, outputAccess),
4691
- ...resolveAlwaysSelectForAccess(snapshot.alwaysSelectFields, docPermissionsAccess)
4692
- ])
4693
- ];
4694
- const joins = [...internal.joinFields ?? [], ...internal.extraPersistedFields ?? []];
4695
- const forced = [...always, ...joins, ...internal.baseFields ?? identity, ...internal.identityFields ?? []];
4696
- const fetchSafe = (path) => isSafeOutputPath(path) && !virtual(full(path));
4697
- const dependencies = Object.keys(depProvenance).filter(fetchSafe);
4698
- const childFetch = Object.entries(children).flatMap(([name, child]) => {
4699
- if (child.persistedFetchSelection.length) return child.persistedFetchSelection.map((p) => `${name}.${p}`);
4700
- depProvenance[name] = allVirtuals.filter((p) => p.startsWith(`${name}.`));
4701
- return [name];
4702
- });
4703
- const publicChildFetch = Object.entries(children).flatMap(
4704
- ([name, child]) => child.publicPersistedFetchSelection.length ? child.publicPersistedFetchSelection.map((path) => `${name}.${path}`) : [name]
4705
- );
4706
- const publicPersistedFetchSelection = compactPersistedProjection([
4707
- ...persisted,
4708
- ...dependencies,
4709
- ...forced.filter(fetchSafe),
4710
- ...identity,
4711
- ...publicChildFetch
4712
- ]);
4713
- const publicStructurePaths = Object.entries(children).flatMap(([name, child]) => {
4714
- if ([...persisted, ...dependencies, ...forced].some((path) => name === path || name.startsWith(`${path}.`)))
4715
- return [];
4716
- return child.publicPersistedFetchSelection.length ? (child.publicStructurePaths ?? []).map((path) => `${name}.${path}`) : [name];
4717
- });
4718
- const populateRefs = candidates.flatMap((candidate) => candidate.populateDependencies.map((dep) => dep.path));
4719
- const privateFields = [...dependencies, ...populateRefs, ...forced.filter(fetchSafe), ...identity, ...childFetch];
4720
- const fetch = compactPersistedProjection([...persisted, ...privateFields]);
4721
- const outputIdExcluded = excludes.includes("_id");
4722
- const coveredOutput = (path) => persisted.some((p) => p === path || path.startsWith(`${p}.`));
4723
- const outputPersisted = [.../* @__PURE__ */ new Set([...persisted.filter((p) => !p.includes(".")), ...Object.keys(children)])];
4724
- return {
4725
- receivingModelName,
4726
- scopePath: [...args.scopePath ?? []],
4727
- responseScopePath: Object.freeze(scope2),
4728
- virtualAccess,
4729
- outputAccess,
4730
- docPermissionsAccess,
4731
- selectionMode: mode,
4732
- effectiveSelectNorm: normalized,
4733
- outputPersistedFields: outputPersisted,
4734
- outputVirtualNames: candidates.map((c) => c.name),
4735
- outputSelection: [...outputPersisted, ...candidates.map((c) => c.name), ...outputIdExcluded ? ["-_id"] : []],
4736
- fieldStates: Object.freeze(states2),
4737
- minimalAncestorPaths: Object.freeze([...ancestors]),
4738
- persistedFetchSelection: fetch,
4739
- publicPersistedFetchSelection,
4740
- publicStructurePaths,
4741
- candidates,
4742
- depProvenance,
4743
- virtualOnlyDeps: Object.keys(depProvenance).filter((p) => fetchSafe(p) && !coveredOutput(p)),
4744
- internalOnlyFields: [
4745
- ...new Set(privateFields.filter((p) => !coveredOutput(p) && (p !== "_id" || outputIdExcluded)))
4746
- ],
4747
- outputIdExcluded,
4748
- fetchIdRetained,
4749
- internalIdentityFields: identity,
4750
- internalJoinFields: [...new Set(joins)],
4751
- childPlans: children,
4752
- // A parent never supplies its authority to a target; related execution will
4753
- // call planAuthorizedModelProjection with the independently derived owner.
4754
- relatedPlans: (args.related ?? []).map(
4755
- (rel) => planVirtualProjection({
4756
- ...rel,
4757
- receivingModelName: rel.targetModelName,
4758
- snapshot: rel.targetSnapshot,
4759
- globalPermissions
4760
- })
4761
- )
4762
- };
5129
+ let state = owners.get(runtime);
5130
+ if (!state) {
5131
+ const limits = resolveRequestComplexity(runtime.getGlobalOption("requestComplexity"));
5132
+ state = {
5133
+ totalQueries: 0,
5134
+ scheduler: new RequestConcurrencyScheduler(limits.maxBulkConcurrency),
5135
+ hookGate: new SharedHookGate(limits.maxHookConcurrency)
5136
+ };
5137
+ owners.set(runtime, state);
5138
+ }
5139
+ return state;
4763
5140
  }
4764
- var init_output_projection = __esm({
4765
- "src/acl/output-projection.ts"() {
4766
- init_query();
4767
- init_authorization_snapshot();
4768
- init_field_catalog();
4769
- init_field_authorization();
4770
- init_virtual_populate_dependencies();
4771
- init_service_authorization();
4772
- init_virtual_projection();
5141
+ var states;
5142
+ var init_request_work = __esm({
5143
+ "src/helpers/request-work.ts"() {
5144
+ init_request_complexity();
5145
+ init_concurrency();
5146
+ states = /* @__PURE__ */ new WeakMap();
4773
5147
  }
4774
5148
  });
4775
5149
 
@@ -4804,6 +5178,8 @@ function captureModelAuthorizationConfiguration(runtime, modelName, options = ru
4804
5178
  exposedDocPermissionKeys: options.exposedDocPermissionKeys,
4805
5179
  stripPermissionsField: options.stripPermissionsField,
4806
5180
  disableFieldPermissions: options.disableFieldPermissions,
5181
+ unsafeSkipListDocumentSnapshotChecks: options.unsafeSkipListDocumentSnapshotChecks === true,
5182
+ unsafeSkipReadDocumentSnapshotChecks: options.unsafeSkipReadDocumentSnapshotChecks === true,
4807
5183
  overrideFilter: options.overrideFilter,
4808
5184
  baseFilter: options.baseFilter,
4809
5185
  idField: options.idField,
@@ -4860,15 +5236,15 @@ import {
4860
5236
  isBoolean as isBoolean2,
4861
5237
  isEmpty as isEmpty2,
4862
5238
  isFunction as isFunction3,
4863
- isPlainObject as isPlainObject17,
5239
+ isPlainObject as isPlainObject18,
4864
5240
  isString as isString5
4865
5241
  } from "@web-ts-toolkit/utils";
4866
5242
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
4867
5243
  function isAndFilter(filter2) {
4868
- return !!filter2 && isPlainObject17(filter2) && Object.keys(filter2).length === 1 && isArray8(filter2.$and);
5244
+ return !!filter2 && isPlainObject18(filter2) && Object.keys(filter2).length === 1 && isArray8(filter2.$and);
4869
5245
  }
4870
5246
  function isMergeableClause(filter2) {
4871
- return !!filter2 && isPlainObject17(filter2) && Object.keys(filter2).every((key) => !key.startsWith("$"));
5247
+ return !!filter2 && isPlainObject18(filter2) && Object.keys(filter2).every((key) => !key.startsWith("$"));
4872
5248
  }
4873
5249
  function optimizeAndFilter(clausesInput) {
4874
5250
  const clauses = [];
@@ -4889,7 +5265,7 @@ function optimizeAndFilter(clausesInput) {
4889
5265
  const entries = Array.from(value, dedupeKey);
4890
5266
  return entries.every((entry) => entry !== void 0) ? `array:${JSON.stringify(entries)}` : void 0;
4891
5267
  }
4892
- if (isPlainObject17(value)) {
5268
+ if (isPlainObject18(value)) {
4893
5269
  const entries = Object.keys(value).sort().map((key) => [key, dedupeKey(value[key])]);
4894
5270
  return entries.every(([, entry]) => entry !== void 0) ? `object:${JSON.stringify(entries)}` : void 0;
4895
5271
  }
@@ -4937,7 +5313,7 @@ function optimizeAndFilter(clausesInput) {
4937
5313
  }
4938
5314
  function normalizeFilter(filter2) {
4939
5315
  if (filter2 === false) return false;
4940
- if (!filter2 || !isPlainObject17(filter2) || isEmpty2(filter2)) return null;
5316
+ if (!filter2 || !isPlainObject18(filter2) || isEmpty2(filter2)) return null;
4941
5317
  if (!isAndFilter(filter2)) {
4942
5318
  return filter2;
4943
5319
  }
@@ -5015,7 +5391,7 @@ async function setRequestPermissions(req) {
5015
5391
  if (hasFieldValue && owner === void 0) return;
5016
5392
  const globalPermissions = getGlobalOption("globalPermissions");
5017
5393
  const permissions = isFunction3(globalPermissions) ? await globalPermissions.call(req, req) : void 0;
5018
- if (isPlainObject17(permissions)) req[requestPermissionField] = permissions;
5394
+ if (isPlainObject18(permissions)) req[requestPermissionField] = permissions;
5019
5395
  else if (isArray8(permissions)) req[requestPermissionField] = arrayToRecord(permissions);
5020
5396
  else if (isString5(permissions)) req[requestPermissionField] = { [permissions]: true };
5021
5397
  else req[requestPermissionField] = {};
@@ -5414,7 +5790,7 @@ var init_filter_resolution = __esm({
5414
5790
  // src/acl/virtual-populate-execution.ts
5415
5791
  import { Document as Document4, mongo as mongo4 } from "mongoose";
5416
5792
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "util";
5417
- import { isPlainObject as isPlainObject20 } from "@web-ts-toolkit/utils";
5793
+ import { isPlainObject as isPlainObject21 } from "@web-ts-toolkit/utils";
5418
5794
  function projectVirtualPopulateView(source, selection, structurePaths = []) {
5419
5795
  const root = { children: /* @__PURE__ */ new Map() };
5420
5796
  for (const path of compactPersistedProjection(selection)) {
@@ -5446,8 +5822,8 @@ function equivalentVirtualPopulatePredicate(left, right) {
5446
5822
  }
5447
5823
  if (Array.isArray(left) || Array.isArray(right))
5448
5824
  return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((entry, index) => equivalentVirtualPopulatePredicate(entry, right[index]));
5449
- if (isPlainObject20(left) || isPlainObject20(right)) {
5450
- if (!isPlainObject20(left) || !isPlainObject20(right)) return false;
5825
+ if (isPlainObject21(left) || isPlainObject21(right)) {
5826
+ if (!isPlainObject21(left) || !isPlainObject21(right)) return false;
5451
5827
  const a = Object.keys(left), b = Object.keys(right);
5452
5828
  return a.length === b.length && a.every(
5453
5829
  (key, index) => key === b[index] && equivalentVirtualPopulatePredicate(
@@ -5850,7 +6226,7 @@ var init_virtual_populate_execution = __esm({
5850
6226
  publicViewIdentities = /* @__PURE__ */ new WeakMap();
5851
6227
  familyRawFetches = /* @__PURE__ */ new WeakMap();
5852
6228
  addressKey = (address) => JSON.stringify(address);
5853
- storage = (value) => value instanceof Document4 ? value._doc : isPlainObject20(value) ? value : void 0;
6229
+ storage = (value) => value instanceof Document4 ? value._doc : isPlainObject21(value) ? value : void 0;
5854
6230
  originalRef = (source, key) => {
5855
6231
  const record3 = storage(source);
5856
6232
  return {
@@ -5877,76 +6253,10 @@ var init_virtual_populate_execution = __esm({
5877
6253
  });
5878
6254
 
5879
6255
  // src/acl/output-field-filter.ts
5880
- import { isPlainObject as isPlainObject21 } from "@web-ts-toolkit/utils";
5881
- function callFieldPolicy(authorization, binding) {
5882
- assertAuthorizationBinding(authorization, binding);
5883
- let policy = fieldPolicies.get(authorization);
5884
- if (!policy) {
5885
- const view = readServiceOutputFieldAuthorization(authorization, binding);
5886
- policy = {
5887
- schema: view.permissionSchema,
5888
- requestPaths: view.permissionSchema == null || isPlainObject21(view.permissionSchema) && Object.isFrozen(view.permissionSchema) ? Object.freeze(Object.keys(view.permissionSchema ?? {})) : void 0,
5889
- prefix: view.modelPermissionPrefix ?? "",
5890
- outputFields: view.outputFields,
5891
- accesses: /* @__PURE__ */ new Map()
5892
- };
5893
- if (view.reusable) fieldPolicies.set(authorization, policy);
5894
- }
5895
- return policy;
5896
- }
5897
- function requestRuleClassification(entry, authorization, permissions, prefix) {
5898
- if (typeof prefix !== "string") return void 0;
5899
- let classification = entry.classifications.get(authorization);
5900
- if (!classification) {
5901
- classification = prepareRequestFieldRule(entry.rule, permissions, prefix);
5902
- entry.classifications.set(authorization, classification);
5903
- }
5904
- return classification;
5905
- }
5906
- function invariantRuleLookup(schema, path) {
5907
- if (schema == null) return true;
5908
- if (!isPlainObject21(schema) || !Object.isFrozen(schema)) return false;
5909
- const exact = Object.getOwnPropertyDescriptor(schema, path);
5910
- if (exact) {
5911
- const raw2 = exact.value;
5912
- return !raw2 || typeof raw2 !== "object" || Array.isArray(raw2) || isPlainObject21(raw2) && Object.isFrozen(raw2);
5913
- }
5914
- const [head, ...rest] = path.split(".");
5915
- const raw = Object.getOwnPropertyDescriptor(schema, head)?.value;
5916
- if (raw == null) return true;
5917
- if (!isPlainObject21(raw) || !Object.isFrozen(raw)) return false;
5918
- const sub = Object.getOwnPropertyDescriptor(raw, "sub");
5919
- return !rest.length || !sub || invariantRuleLookup(sub.value, rest.join("."));
5920
- }
5921
- function prepareOutputPath(policy, authorization, binding, path, access) {
5922
- let cache = policy.accesses.get(access);
5923
- if (!cache) {
5924
- cache = /* @__PURE__ */ new Map();
5925
- policy.accesses.set(access, cache);
5926
- }
5927
- let prepared = cache.get(path);
5928
- if (!prepared) {
5929
- const invariant = invariantRuleLookup(policy.schema, path);
5930
- const permissions = getAuthorizationPermissions(authorization, binding);
5931
- const entries = extractOutputFieldRuleEntries(policy.schema, path, access).map((entry) => ({
5932
- ...entry,
5933
- classifications: /* @__PURE__ */ new WeakMap()
5934
- }));
5935
- const classifications = entries.map(
5936
- (entry) => requestRuleClassification(entry, authorization, permissions, policy.prefix)
5937
- );
5938
- const backendGrant = hasExplicitFieldGrant(policy.outputFields, path);
5939
- prepared = {
5940
- entries,
5941
- backendGrant,
5942
- state: backendGrant ? "granted" : classifications.every((value) => value !== void 0) ? combineFieldAuthorizationStates(classifications.map((value) => value.state)) : void 0
5943
- };
5944
- if (invariant) cache.set(path, prepared);
5945
- }
5946
- return prepared;
5947
- }
6256
+ import { types as types5 } from "util";
6257
+ import { isPlainObject as isPlainObject22 } from "@web-ts-toolkit/utils";
5948
6258
  function assertOwningOutputDocuments(handle) {
5949
- const owner = owningDocuments.get(handle);
6259
+ const owner = readOutputDocumentOwner(handle);
5950
6260
  if (owner) {
5951
6261
  readDocumentAuthorizationAccess(owner.handle, owner.binding);
5952
6262
  assertOwningOutputDocuments(owner.handle);
@@ -5956,7 +6266,7 @@ function prepareOutputDocumentAuthorization(authorization, binding, configuratio
5956
6266
  const access = readServiceAuthorizationAccess(authorization, binding);
5957
6267
  const key = `docPermissions.${access.docPermissionsAccess}`;
5958
6268
  const docPermissions = configuration.docPermissions;
5959
- const invariant = /^[A-Za-z0-9_-]+$/.test(access.docPermissionsAccess) && (docPermissions == null || isPlainObject21(docPermissions));
6269
+ const invariant = /^[A-Za-z0-9_-]+$/.test(access.docPermissionsAccess) && (docPermissions == null || isPlainObject22(docPermissions));
5960
6270
  const option = invariant ? getCapturedAuthorizationOption(configuration, key) : void 0;
5961
6271
  const hook = typeof option === "function" ? option : void 0;
5962
6272
  const resolveHook = invariant ? () => hook : () => {
@@ -5986,7 +6296,7 @@ async function resolveOutputDocumentAuthorizationWithHook(args, access, resolveH
5986
6296
  try {
5987
6297
  const run = () => hook.call(this, doc, permissions, args.context);
5988
6298
  const grants = await getRequestWorkState(binding.request, binding.runtime).hookGate.run(run);
5989
- return isPlainObject21(grants) ? grants : {};
6299
+ return isPlainObject22(grants) ? grants : {};
5990
6300
  } catch (error2) {
5991
6301
  warn("docPermissions hook failed; applying empty document permissions", {
5992
6302
  modelName: binding.modelName,
@@ -5997,14 +6307,12 @@ async function resolveOutputDocumentAuthorizationWithHook(args, access, resolveH
5997
6307
  return {};
5998
6308
  }
5999
6309
  });
6000
- if (args.knownOutput || args.owningDocument && unresolvedDocuments.has(args.owningDocument))
6001
- unresolvedDocuments.add(handle);
6002
- if (args.owningDocument) owningDocuments.set(handle, { handle: args.owningDocument, binding: args.owningBinding });
6310
+ bindOutputDocumentOwner(handle, args.knownOutput, args.owningDocument, args.owningBinding);
6003
6311
  return handle;
6004
6312
  }
6005
6313
  function evaluateRequestRule(handle, binding, entry, prefix, access) {
6006
6314
  assertOwningOutputDocuments(handle);
6007
- const owner = owningDocuments.get(handle);
6315
+ const owner = readOutputDocumentOwner(handle);
6008
6316
  if (owner && !entry.path.startsWith(`${(binding.scopePath ?? []).join(".")}.`)) {
6009
6317
  return evaluateRequestRule(owner.handle, owner.binding, entry, prefix, access);
6010
6318
  }
@@ -6038,7 +6346,7 @@ function evaluateAuthorizedOutputField(handle, binding, field) {
6038
6346
  const policy = callFieldPolicy(authorization, binding);
6039
6347
  const { outputAccess } = readDocumentAuthorizationAccess(handle, binding);
6040
6348
  const prepared = prepareOutputPath(policy, authorization, binding, path, outputAccess);
6041
- const unresolved = unresolvedDocuments.has(handle);
6349
+ const unresolved = isUnresolvedOutputDocument(handle);
6042
6350
  const state = unresolved ? prepared.state ?? classifyEffectiveFieldAuthorization({
6043
6351
  path,
6044
6352
  rules: prepared.entries.map((entry) => entry.rule),
@@ -6061,12 +6369,18 @@ function evaluateAuthorizedOutputField(handle, binding, field) {
6061
6369
  assertOwningOutputDocuments(handle);
6062
6370
  return allowed;
6063
6371
  });
6064
- return owningDocuments.has(handle) ? decision.then((allowed) => {
6372
+ return readOutputDocumentOwner(handle) ? decision.then((allowed) => {
6065
6373
  assertOwningOutputDocuments(handle);
6066
6374
  return allowed;
6067
6375
  }) : decision;
6068
6376
  }
6069
6377
  async function requestOutputFieldPaths(handle, binding, access) {
6378
+ const staticFields = tryStaticRequestFieldPaths(handle, binding, access);
6379
+ if (staticFields) {
6380
+ await Promise.resolve();
6381
+ readDocumentAuthorizationAccess(handle, binding);
6382
+ return staticFields;
6383
+ }
6070
6384
  const { authorization } = readDocumentAuthorizationAccess(handle, binding);
6071
6385
  assertOwningOutputDocuments(handle);
6072
6386
  const policy = callFieldPolicy(authorization, binding);
@@ -6115,7 +6429,7 @@ function copyOutputValue(value, plan, path) {
6115
6429
  const visit = (input, current) => {
6116
6430
  if (Array.isArray(input)) return input.map((entry) => visit(entry, current));
6117
6431
  if (input instanceof Map) return visit(Object.fromEntries(input), current);
6118
- if (!isPlainObject21(input)) return deepIsolateValue(input);
6432
+ if (!isPlainObject22(input)) return deepIsolateValue(input);
6119
6433
  const output = {};
6120
6434
  for (const [key, entry] of Object.entries(input)) {
6121
6435
  const child = `${current}.${key}`;
@@ -6131,7 +6445,7 @@ function copyOutputValue(value, plan, path) {
6131
6445
  }
6132
6446
  function copyAuthorizedReference(value, plan, path) {
6133
6447
  if (Array.isArray(value)) return value.map((entry) => copyAuthorizedReference(entry, plan, path));
6134
- if (!isPlainObject21(value)) return deepIsolateValue(value);
6448
+ if (!isPlainObject22(value)) return deepIsolateValue(value);
6135
6449
  const handle = getAssociatedDocumentAuthorization(value, plan.authorization);
6136
6450
  if (handle) {
6137
6451
  const copy = deepIsolateValue(value);
@@ -6144,8 +6458,8 @@ function retainOutputMetadata(output, source, configuration, scope2) {
6144
6458
  if (scope2.length || configuration.stripPermissionsField) return;
6145
6459
  const parts = (configuration.documentPermissionField ?? "_permissions").split(".");
6146
6460
  let value = source;
6147
- for (const part of parts) value = isPlainObject21(value) ? value[part] : void 0;
6148
- if (!isPlainObject21(value)) return;
6461
+ for (const part of parts) value = isPlainObject22(value) ? value[part] : void 0;
6462
+ if (!isPlainObject22(value)) return;
6149
6463
  const keys2 = configuration.exposedDocPermissionKeys;
6150
6464
  const metadata = Object.fromEntries(
6151
6465
  Object.entries(value).filter(
@@ -6155,7 +6469,7 @@ function retainOutputMetadata(output, source, configuration, scope2) {
6155
6469
  const copy = { ...output };
6156
6470
  let target = copy;
6157
6471
  for (const part of parts.slice(0, -1)) {
6158
- target[part] = isPlainObject21(target[part]) ? { ...target[part] } : {};
6472
+ target[part] = isPlainObject22(target[part]) ? { ...target[part] } : {};
6159
6473
  target = target[part];
6160
6474
  }
6161
6475
  target[parts[parts.length - 1]] = deepIsolateValue(metadata);
@@ -6164,27 +6478,37 @@ function retainOutputMetadata(output, source, configuration, scope2) {
6164
6478
  attachPermissionsAlias(output, parts.join("."));
6165
6479
  }
6166
6480
  function helperPlan(authorization, binding) {
6167
- const { configuration, authorization: policy, access } = readServiceAuthorization(authorization, binding);
6168
- if (binding.scopePath?.length && !isCatalogOutputPath(configuration.catalog, binding.scopePath.join(".")))
6169
- authorizationError("unknown output scope");
6170
- const plan = planCatalogProjection(
6171
- {
6172
- receivingModelName: binding.modelName,
6173
- snapshot: configuration,
6174
- ...access,
6175
- effectiveSelect: [],
6176
- scopePath: (binding.scopePath ?? []).flatMap((part) => [part, "sub"]),
6177
- globalPermissions: getAuthorizationPermissions(authorization, binding)
6178
- },
6179
- policy.outputFields
6180
- );
6181
- return { ...plan, authorization, authorizationBinding: binding };
6481
+ return planAuthorizedModelProjection({ authorization, binding, effectiveSelect: [] });
6482
+ }
6483
+ function primitiveHelperFields(source, plan) {
6484
+ if (types5.isProxy(source)) return;
6485
+ const canonical = readStaticOutputPlanFields(plan, plan.authorization);
6486
+ if (!canonical) return;
6487
+ const fields = [];
6488
+ for (const field of canonical) {
6489
+ const slot = Object.getOwnPropertyDescriptor(source, field);
6490
+ if (!slot) continue;
6491
+ if (!("value" in slot)) return;
6492
+ const value = slot.value;
6493
+ if (value !== null && typeof value === "object" || typeof value === "function" || typeof value === "symbol")
6494
+ return;
6495
+ if (value !== void 0) fields.push(field);
6496
+ }
6497
+ return fields;
6182
6498
  }
6183
6499
  async function filterExistingOutput(source, plan, handle, associated) {
6184
6500
  const binding = plan.authorizationBinding;
6185
6501
  const { configuration } = readServiceAuthorization(plan.authorization, binding);
6186
6502
  const output = {};
6187
6503
  const fields = [];
6504
+ const primitiveFields = primitiveHelperFields(source, plan);
6505
+ const staticDecisions = primitiveFields && tryStaticOutputFieldDecisions(handle, binding, plan, primitiveFields);
6506
+ if (staticDecisions) {
6507
+ await Promise.resolve();
6508
+ if (associated) assertDocumentAuthorization(handle, { binding, output: source, outputAccess: plan.outputAccess });
6509
+ else readDocumentAuthorizationAccess(handle, binding);
6510
+ if (!readStaticOutputPlanFields(plan, plan.authorization)) authorizationError("changed static output plan");
6511
+ }
6188
6512
  for (const field of /* @__PURE__ */ new Set([...plan.outputPersistedFields, ...plan.outputVirtualNames])) {
6189
6513
  if (!Object.prototype.hasOwnProperty.call(source, field) || source[field] === void 0) continue;
6190
6514
  const childPlan = plan.childPlans[field];
@@ -6197,7 +6521,7 @@ async function filterExistingOutput(source, plan, handle, associated) {
6197
6521
  for (const entry of value2) values.push(await one(entry) ?? null);
6198
6522
  return values;
6199
6523
  }
6200
- if (!isPlainObject21(value2)) return value2 === null ? null : void 0;
6524
+ if (!isPlainObject22(value2)) return value2 === null ? null : void 0;
6201
6525
  const childHandle = associated ? getAssociatedDocumentAuthorization(value2) : void 0;
6202
6526
  let child = scoped;
6203
6527
  if (childHandle) {
@@ -6225,7 +6549,7 @@ async function filterExistingOutput(source, plan, handle, associated) {
6225
6549
  const value = await one(source[field]);
6226
6550
  if (value !== void 0) output[field] = value;
6227
6551
  fields.push(...childFields);
6228
- } else if (await evaluateAuthorizedOutputField(handle, binding, field)) {
6552
+ } else if (staticDecisions ? staticDecisions.get(field) === true : await evaluateAuthorizedOutputField(handle, binding, field)) {
6229
6553
  const path = [...binding.scopePath ?? [], field].join(".");
6230
6554
  output[field] = configuration.catalog.referencePaths?.some((p) => matchesCatalogPattern(p, path)) ? copyAuthorizedReference(source[field], plan, path) : copyOutputValue(source[field], plan, path);
6231
6555
  if (associated) transferDocumentAuthorizationGraph(source[field], output[field]);
@@ -6277,7 +6601,7 @@ async function filterModelOutputForHelper(args) {
6277
6601
  const plan = helperPlan(normalized.authorization, binding);
6278
6602
  if (args.doc == null) return { output: args.doc, fields: [] };
6279
6603
  const source = isolateDocForOutput(args.doc);
6280
- if (!isPlainObject21(source)) return authorizationError("output helper requires one plain or hydrated document");
6604
+ if (!isPlainObject22(source)) return authorizationError("output helper requires one plain or hydrated document");
6281
6605
  const knownOutput = !!args.doc && typeof args.doc === "object" && isKnownAuthorizationOutput(args.doc);
6282
6606
  const handle = await resolveOutputDocumentAuthorization({
6283
6607
  authorization: normalized.authorization,
@@ -6288,7 +6612,6 @@ async function filterModelOutputForHelper(args) {
6288
6612
  });
6289
6613
  return filterExistingOutput(source, plan, handle, false);
6290
6614
  }
6291
- var unresolvedDocuments, owningDocuments, fieldPolicies;
6292
6615
  var init_output_field_filter = __esm({
6293
6616
  "src/acl/output-field-filter.ts"() {
6294
6617
  init_permissions_alias();
@@ -6302,9 +6625,7 @@ var init_output_field_filter = __esm({
6302
6625
  init_field_authorization();
6303
6626
  init_field_catalog();
6304
6627
  init_output_projection();
6305
- unresolvedDocuments = /* @__PURE__ */ new WeakSet();
6306
- owningDocuments = /* @__PURE__ */ new WeakMap();
6307
- fieldPolicies = /* @__PURE__ */ new WeakMap();
6628
+ init_output_field_policy();
6308
6629
  }
6309
6630
  });
6310
6631
 
@@ -6373,7 +6694,7 @@ __export(finalize_model_output_exports, {
6373
6694
  finalizeModelOutput: () => finalizeModelOutput,
6374
6695
  finalizeModelOutputs: () => finalizeModelOutputs
6375
6696
  });
6376
- import { get as get9, isPlainObject as isPlainObject22, set as set7 } from "@web-ts-toolkit/utils";
6697
+ import { get as get9, isPlainObject as isPlainObject23, set as set7 } from "@web-ts-toolkit/utils";
6377
6698
  function assertFinalizerCall(args, prepared) {
6378
6699
  const plan = args.plan;
6379
6700
  const binding = plan.authorizationBinding;
@@ -6415,8 +6736,8 @@ async function finalizeSingleDoc(args, input, prepared) {
6415
6736
  const privateRow = args.virtualPopulateRow ?? (original && typeof original === "object" ? getVirtualPopulateRow(original) : void 0);
6416
6737
  const privateAddress = args.virtualPopulateAddress ?? [];
6417
6738
  const isolated = isolateDocForOutput(input);
6418
- const output = isPlainObject22(isolated) ? isolated : {};
6419
- if (captured && isPlainObject22(input))
6739
+ const output = isPlainObject23(isolated) ? isolated : {};
6740
+ if (captured && isPlainObject23(input))
6420
6741
  for (const key of Object.keys(output)) {
6421
6742
  transferDocumentAuthorizationGraph(input[key], output[key]);
6422
6743
  }
@@ -6468,7 +6789,7 @@ async function finalizeSingleDoc(args, input, prepared) {
6468
6789
  );
6469
6790
  continue;
6470
6791
  }
6471
- if (captured && !isPlainObject22(rawContainer) && !Array.isArray(rawContainer)) {
6792
+ if (captured && !isPlainObject23(rawContainer) && !Array.isArray(rawContainer)) {
6472
6793
  delete output[containerName];
6473
6794
  continue;
6474
6795
  }
@@ -6494,7 +6815,7 @@ async function finalizeSingleDoc(args, input, prepared) {
6494
6815
  const finalizeOneChild = async (rawChild, address) => {
6495
6816
  if (captured && Array.isArray(rawChild))
6496
6817
  return mapWithConcurrencyLimit(rawChild, limit, (entry, index) => finalizeOneChild(entry, [...address, index]));
6497
- if (!isPlainObject22(rawChild) && !Array.isArray(rawChild)) return captured ? null : deepIsolateValue(rawChild);
6818
+ if (!isPlainObject23(rawChild) && !Array.isArray(rawChild)) return captured ? null : deepIsolateValue(rawChild);
6498
6819
  if (args.traversal?.finalizeEmbeddedChildren) {
6499
6820
  return args.traversal.finalizeEmbeddedChildren({
6500
6821
  containerName,
@@ -6527,7 +6848,7 @@ async function finalizeSingleDoc(args, input, prepared) {
6527
6848
  (entry, index) => finalizeOneChild(entry, [...privateAddress, containerName, index])
6528
6849
  );
6529
6850
  output[containerName] = finalized;
6530
- } else if (isPlainObject22(rawContainer)) {
6851
+ } else if (isPlainObject23(rawContainer)) {
6531
6852
  output[containerName] = await finalizeOneChild(rawContainer, [
6532
6853
  ...privateAddress,
6533
6854
  containerName
@@ -6572,7 +6893,7 @@ async function finalizeSingleDoc(args, input, prepared) {
6572
6893
  };
6573
6894
  let relatedPreparation;
6574
6895
  const finalizeOneRelated = async (rawChild, originalChild = rawChild) => {
6575
- if (!isPlainObject22(rawChild) && !Array.isArray(rawChild)) return rawChild;
6896
+ if (!isPlainObject23(rawChild) && !Array.isArray(rawChild)) return rawChild;
6576
6897
  if (typeof rawChild?._bsontype === "string") return rawChild;
6577
6898
  const childOriginal = getIncludeOriginal(originalChild);
6578
6899
  const childRow = childOriginal && typeof childOriginal === "object" ? getVirtualPopulateRow(childOriginal) : void 0;
@@ -6597,7 +6918,7 @@ async function finalizeSingleDoc(args, input, prepared) {
6597
6918
  limit,
6598
6919
  (entry, index) => finalizeOneRelated(entry, Array.isArray(originalRelated) ? originalRelated[index] : void 0)
6599
6920
  );
6600
- } else if (isPlainObject22(rawRelated)) {
6921
+ } else if (isPlainObject23(rawRelated)) {
6601
6922
  finalized = await finalizeOneRelated(rawRelated, originalRelated);
6602
6923
  } else {
6603
6924
  continue;
@@ -6682,10 +7003,17 @@ async function finalizeSingleDoc(args, input, prepared) {
6682
7003
  }
6683
7004
  const eligiblePersisted = new Set(plan.outputPersistedFields ?? []);
6684
7005
  const eligibleVirtuals = new Set(plan.outputVirtualNames ?? []);
7006
+ const staticDecisions = documentAuthorization ? tryStaticOutputFieldDecisions(documentAuthorization, binding, plan, [...eligiblePersisted]) : void 0;
7007
+ if (staticDecisions) {
7008
+ await Promise.resolve();
7009
+ assertFinalizerCall(args, prepared);
7010
+ readDocumentAuthorizationAccess(documentAuthorization, binding);
7011
+ if (!readStaticOutputPlanFields(plan, prepared.authorization)) authorizationError("changed static output plan");
7012
+ }
6685
7013
  const allowedPersisted = [];
6686
7014
  for (const field of eligiblePersisted) {
6687
7015
  if (documentAuthorization) {
6688
- if (plan.childPlans[field] || await evaluateAuthorizedOutputField(documentAuthorization, binding, field))
7016
+ if (plan.childPlans[field] || (staticDecisions ? staticDecisions.get(field) === true : await evaluateAuthorizedOutputField(documentAuthorization, binding, field)))
6689
7017
  allowedPersisted.push(field);
6690
7018
  continue;
6691
7019
  }
@@ -6763,6 +7091,10 @@ async function finalizeSingleDoc(args, input, prepared) {
6763
7091
  stage: readDocumentAuthorizationAccess(documentAuthorization, binding).stage
6764
7092
  })
6765
7093
  );
7094
+ if (staticDecisions) {
7095
+ assertFinalizerCall(args, prepared);
7096
+ readDocumentAuthorizationAccess(documentAuthorization, binding);
7097
+ }
6766
7098
  }
6767
7099
  void getRetainedAssociations;
6768
7100
  return trimmed;
@@ -6823,22 +7155,23 @@ var init_finalize_model_output = __esm({
6823
7155
  init_output_field_filter();
6824
7156
  init_field_authorization();
6825
7157
  init_field_catalog();
7158
+ init_output_projection();
6826
7159
  init_virtual_populate_execution();
6827
7160
  init_include_output();
6828
- isVirtualContainerValue3 = (value) => isPlainObject22(value) && "sub" in value;
7161
+ isVirtualContainerValue3 = (value) => isPlainObject23(value) && "sub" in value;
6829
7162
  getScopeVirtualsObject2 = (rootVirtuals, scopePath) => {
6830
- if (!rootVirtuals || !isPlainObject22(rootVirtuals)) return null;
7163
+ if (!rootVirtuals || !isPlainObject23(rootVirtuals)) return null;
6831
7164
  if (scopePath.length === 0) return rootVirtuals;
6832
7165
  let current = rootVirtuals;
6833
7166
  for (let i = 0; i < scopePath.length; i += 2) {
6834
7167
  const field = scopePath[i];
6835
7168
  const subMarker = scopePath[i + 1];
6836
7169
  if (!field || subMarker !== "sub") return null;
6837
- if (!isPlainObject22(current)) return null;
7170
+ if (!isPlainObject23(current)) return null;
6838
7171
  const container = current[field];
6839
7172
  if (!isVirtualContainerValue3(container)) return null;
6840
7173
  current = container.sub;
6841
- if (!isPlainObject22(current)) return null;
7174
+ if (!isPlainObject23(current)) return null;
6842
7175
  }
6843
7176
  return current;
6844
7177
  };
@@ -6851,11 +7184,11 @@ var init_finalize_model_output = __esm({
6851
7184
  return Object.entries(scopeVirtuals).filter(([, v]) => v !== void 0 && !isVirtualContainerValue3(v)).map(([k]) => k);
6852
7185
  };
6853
7186
  getScopedPermissionSchema2 = (root, scopePath) => {
6854
- if (!root || !isPlainObject22(root)) return null;
7187
+ if (!root || !isPlainObject23(root)) return null;
6855
7188
  if (scopePath.length === 0) return root;
6856
7189
  try {
6857
7190
  const scoped = get9(root, scopePath.join("."));
6858
- return isPlainObject22(scoped) ? scoped : null;
7191
+ return isPlainObject23(scoped) ? scoped : null;
6859
7192
  } catch {
6860
7193
  return null;
6861
7194
  }
@@ -6914,7 +7247,7 @@ var init_finalize_model_output = __esm({
6914
7247
  const grants = await args.sharedGate.run(
6915
7248
  () => hook.call(args.request, isolatedForHook, globalPerms, scopeContext)
6916
7249
  );
6917
- const normalized = isPlainObject22(grants) ? grants : {};
7250
+ const normalized = isPlainObject23(grants) ? grants : {};
6918
7251
  scopeContext.docPermissions = normalized;
6919
7252
  return normalized;
6920
7253
  }
@@ -6936,11 +7269,11 @@ var init_finalize_model_output = __esm({
6936
7269
  });
6937
7270
 
6938
7271
  // src/index.ts
6939
- import { isPlainObject as isPlainObject31, isString as isString10, isUndefined as isUndefined4 } from "@web-ts-toolkit/utils";
7272
+ import { isPlainObject as isPlainObject32, isString as isString10, isUndefined as isUndefined4 } from "@web-ts-toolkit/utils";
6940
7273
 
6941
7274
  // src/middleware.ts
6942
7275
  import JsonRouter5 from "@web-ts-toolkit/express-json-router";
6943
- import { isArray as isArray13, isFunction as isFunction7, isPlainObject as isPlainObject27, isString as isString7 } from "@web-ts-toolkit/utils";
7276
+ import { isArray as isArray13, isFunction as isFunction7, isPlainObject as isPlainObject28, isString as isString7 } from "@web-ts-toolkit/utils";
6944
7277
 
6945
7278
  // src/core.ts
6946
7279
  init_public_admission();
@@ -6975,7 +7308,7 @@ import {
6975
7308
  forEach as forEach3,
6976
7309
  get as get8,
6977
7310
  isArray as isArray9,
6978
- isPlainObject as isPlainObject18,
7311
+ isPlainObject as isPlainObject19,
6979
7312
  set as set6,
6980
7313
  uniq
6981
7314
  } from "@web-ts-toolkit/utils";
@@ -7100,7 +7433,7 @@ init_public_admission();
7100
7433
  // src/correlated-includes.ts
7101
7434
  init_request_complexity();
7102
7435
  init_sort_policy();
7103
- import { cloneDeep, isArray as isArray6, isPlainObject as isPlainObject15 } from "@web-ts-toolkit/utils";
7436
+ import { cloneDeep, isArray as isArray7, isPlainObject as isPlainObject17 } from "@web-ts-toolkit/utils";
7104
7437
  var PARENT_MARKER_KEY = "$parent";
7105
7438
  var ESCAPE_WRAPPER_KEY = "$escape";
7106
7439
  var SUBQUERY_PAYLOAD_KEYS = /* @__PURE__ */ new Set(["$$sq", "$$date"]);
@@ -7111,10 +7444,10 @@ var FIELD_SEGMENT_PATTERN = /^[A-Za-z_][A-Za-z0-9_$]*$/;
7111
7444
  var ARRAY_INDEX_SEGMENT_PATTERN = /^(0|[1-9]\d*)$/;
7112
7445
  var ownKeys = (value) => Object.keys(value);
7113
7446
  function isParentRefMarker(value) {
7114
- return isPlainObject15(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === PARENT_MARKER_KEY;
7447
+ return isPlainObject17(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === PARENT_MARKER_KEY;
7115
7448
  }
7116
7449
  function isEscapedParentRef(value) {
7117
- return isPlainObject15(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === ESCAPE_WRAPPER_KEY;
7450
+ return isPlainObject17(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === ESCAPE_WRAPPER_KEY;
7118
7451
  }
7119
7452
  function hasMarkerKey(value) {
7120
7453
  return ownKeys(value).includes(PARENT_MARKER_KEY) || ownKeys(value).includes(ESCAPE_WRAPPER_KEY);
@@ -7133,12 +7466,12 @@ function containsParentMarkerShape(value) {
7133
7466
  const seen = /* @__PURE__ */ new Set();
7134
7467
  const visit = (current) => {
7135
7468
  if (isParentRefMarker(current) || isEscapedParentRef(current)) return true;
7136
- if (isArray6(current)) {
7469
+ if (isArray7(current)) {
7137
7470
  if (seen.has(current)) return false;
7138
7471
  seen.add(current);
7139
7472
  return current.some(visit);
7140
7473
  }
7141
- if (isPlainObject15(current)) {
7474
+ if (isPlainObject17(current)) {
7142
7475
  if (seen.has(current)) return false;
7143
7476
  seen.add(current);
7144
7477
  if (hasMarkerKey(current)) return true;
@@ -7168,7 +7501,7 @@ function scanTemplateValueNode(value, path, issues) {
7168
7501
  }
7169
7502
  return;
7170
7503
  }
7171
- if (isPlainObject15(value)) {
7504
+ if (isPlainObject17(value)) {
7172
7505
  if (hasMarkerKey(value)) {
7173
7506
  issues.push({
7174
7507
  message: 'Malformed $parent reference: objects carrying $parent must be exactly { "$parent": "<field>" }',
@@ -7179,7 +7512,7 @@ function scanTemplateValueNode(value, path, issues) {
7179
7512
  scanTemplateObjectEntries(value, path, issues);
7180
7513
  return;
7181
7514
  }
7182
- if (isArray6(value)) {
7515
+ if (isArray7(value)) {
7183
7516
  value.forEach((item, index) => scanTemplateValueNode(item, [...path, index], issues));
7184
7517
  }
7185
7518
  }
@@ -7220,7 +7553,7 @@ function scanTemplateObjectEntries(obj, basePath, issues) {
7220
7553
  continue;
7221
7554
  }
7222
7555
  if (LOGICAL_CLAUSE_KEYS.has(key)) {
7223
- if (!isArray6(child)) {
7556
+ if (!isArray7(child)) {
7224
7557
  scanTemplateValueNode(child, childPath, issues);
7225
7558
  continue;
7226
7559
  }
@@ -7233,7 +7566,7 @@ function scanTemplateObjectEntries(obj, basePath, issues) {
7233
7566
  });
7234
7567
  return;
7235
7568
  }
7236
- if (isPlainObject15(clause)) {
7569
+ if (isPlainObject17(clause)) {
7237
7570
  scanTemplateObjectEntries(clause, clausePath, issues);
7238
7571
  }
7239
7572
  });
@@ -7244,7 +7577,7 @@ function scanTemplateObjectEntries(obj, basePath, issues) {
7244
7577
  }
7245
7578
  function validateCorrelatedFilterTemplate(filter2) {
7246
7579
  const issues = [];
7247
- if (!isPlainObject15(filter2)) {
7580
+ if (!isPlainObject17(filter2)) {
7248
7581
  issues.push({ message: "Correlated include filter must be an object", path: [] });
7249
7582
  return issues;
7250
7583
  }
@@ -7287,13 +7620,13 @@ function collectFilterReferencePaths(filter2) {
7287
7620
  return;
7288
7621
  }
7289
7622
  if (isEscapedParentRef(value)) return;
7290
- if (isArray6(value)) {
7623
+ if (isArray7(value)) {
7291
7624
  if (seen.has(value)) return;
7292
7625
  seen.add(value);
7293
7626
  value.forEach(visitValue);
7294
7627
  return;
7295
7628
  }
7296
- if (isPlainObject15(value)) {
7629
+ if (isPlainObject17(value)) {
7297
7630
  if (seen.has(value)) return;
7298
7631
  seen.add(value);
7299
7632
  for (const [key, child] of Object.entries(value)) {
@@ -7339,7 +7672,7 @@ function getOwnPathValue(parent, path) {
7339
7672
  return current;
7340
7673
  }
7341
7674
  function cloneSubstitutedValue(value) {
7342
- if (isPlainObject15(value) || isArray6(value)) return cloneDeep(value);
7675
+ if (isPlainObject17(value) || isArray7(value)) return cloneDeep(value);
7343
7676
  return value;
7344
7677
  }
7345
7678
  function literalParentRefObject(path) {
@@ -7380,7 +7713,7 @@ function resolveObjectEntries(obj, parent) {
7380
7713
  continue;
7381
7714
  }
7382
7715
  if (LOGICAL_CLAUSE_KEYS.has(key)) {
7383
- if (!isArray6(child)) {
7716
+ if (!isArray7(child)) {
7384
7717
  out[key] = resolveValueNode(child, parent, false);
7385
7718
  continue;
7386
7719
  }
@@ -7388,7 +7721,7 @@ function resolveObjectEntries(obj, parent) {
7388
7721
  if (isParentRefMarker(clause) || isEscapedParentRef(clause)) {
7389
7722
  throw new CorrelatedReferenceError(`Unsupported $parent reference as a direct ${key} clause`);
7390
7723
  }
7391
- if (!isPlainObject15(clause)) return cloneSubstitutedValue(clause);
7724
+ if (!isPlainObject17(clause)) return cloneSubstitutedValue(clause);
7392
7725
  return resolveObjectEntries(clause, parent);
7393
7726
  });
7394
7727
  continue;
@@ -7417,10 +7750,10 @@ function resolveValueNode(template, parent, bare) {
7417
7750
  }
7418
7751
  const value = getOwnPathValue(parent, path);
7419
7752
  if (value === void 0 || value === null) throw UNRESOLVABLE;
7420
- if (bare && isPlainObject15(value)) return { $eq: cloneDeep(value) };
7753
+ if (bare && isPlainObject17(value)) return { $eq: cloneDeep(value) };
7421
7754
  return cloneSubstitutedValue(value);
7422
7755
  }
7423
- if (isPlainObject15(template)) {
7756
+ if (isPlainObject17(template)) {
7424
7757
  if (hasMarkerKey(template)) {
7425
7758
  throw new CorrelatedReferenceError(
7426
7759
  'Malformed $parent reference: objects carrying $parent must be exactly { "$parent": "<field>" }'
@@ -7428,7 +7761,7 @@ function resolveValueNode(template, parent, bare) {
7428
7761
  }
7429
7762
  return resolveObjectEntries(template, parent);
7430
7763
  }
7431
- if (isArray6(template)) {
7764
+ if (isArray7(template)) {
7432
7765
  return template.map((item) => resolveValueNode(item, parent, false));
7433
7766
  }
7434
7767
  return template;
@@ -7462,7 +7795,7 @@ function resolveCorrelatedIdTemplate(id, parent) {
7462
7795
  }
7463
7796
  function resolveCorrelatedFilterTemplate(filter2, parent) {
7464
7797
  try {
7465
- if (!isPlainObject15(filter2) || isParentRefMarker(filter2) || isEscapedParentRef(filter2)) {
7798
+ if (!isPlainObject17(filter2) || isParentRefMarker(filter2) || isEscapedParentRef(filter2)) {
7466
7799
  throw new CorrelatedReferenceError("Correlated include filter must be an object");
7467
7800
  }
7468
7801
  return { status: "resolved", filter: resolveObjectEntries(filter2, parent) };
@@ -7477,7 +7810,7 @@ function validateExpandedCorrelatedOperands(expanded, limits) {
7477
7810
  var MAX_NESTED_INCLUDE_DEPTH = 10;
7478
7811
  function validateCorrelatedArgsShape(args, op, depth) {
7479
7812
  if (args === void 0) return [];
7480
- if (!isPlainObject15(args)) return ["Correlated include args must be an object"];
7813
+ if (!isPlainObject17(args)) return ["Correlated include args must be an object"];
7481
7814
  const record3 = args;
7482
7815
  const allowed = op === "list" ? /* @__PURE__ */ new Set(["select", "sort", "skip", "limit", "page", "pageSize", "include"]) : /* @__PURE__ */ new Set(["select", "sort", "include"]);
7483
7816
  for (const key of Object.keys(record3)) {
@@ -7499,7 +7832,7 @@ function validateCorrelatedArgsShape(args, op, depth) {
7499
7832
  return [];
7500
7833
  }
7501
7834
  function validateCorrelatedIncludeShape(entry, depth = 0) {
7502
- if (!isPlainObject15(entry)) return ["Correlated include must be an object"];
7835
+ if (!isPlainObject17(entry)) return ["Correlated include must be an object"];
7503
7836
  const record3 = entry;
7504
7837
  if (record3.mode !== "correlated") return ['Correlated include mode must be "correlated"'];
7505
7838
  if (typeof record3.model !== "string" || record3.model.length === 0)
@@ -7512,7 +7845,7 @@ function validateCorrelatedIncludeShape(entry, depth = 0) {
7512
7845
  if ("localField" in record3 || "foreignField" in record3) {
7513
7846
  return ["Correlated includes must not carry localField or foreignField"];
7514
7847
  }
7515
- if (record3.options !== void 0 && !(isPlainObject15(record3.options) && Object.keys(record3.options).length === 0)) {
7848
+ if (record3.options !== void 0 && !(isPlainObject17(record3.options) && Object.keys(record3.options).length === 0)) {
7516
7849
  return ["Correlated include options must be absent or empty"];
7517
7850
  }
7518
7851
  const hasId = record3.id !== void 0;
@@ -7534,7 +7867,7 @@ function validateCorrelatedIncludeShape(entry, depth = 0) {
7534
7867
  return validateCorrelatedArgsShape(record3.args, record3.op, depth);
7535
7868
  }
7536
7869
  function isCorrelatedInclude(value) {
7537
- return isPlainObject15(value) && value.mode === "correlated";
7870
+ return isPlainObject17(value) && value.mode === "correlated";
7538
7871
  }
7539
7872
 
7540
7873
  // src/services/base.ts
@@ -7811,7 +8144,9 @@ function createServiceExecution(receiver, access, authorization, applicability =
7811
8144
  relatedTargets,
7812
8145
  parent,
7813
8146
  configuration: configuration ?? registered.configuration(),
7814
- requestPermissions: requestPermissions ?? registered.permissions()
8147
+ requestPermissions: requestPermissions ?? registered.permissions(),
8148
+ listResponse: access.operation === "list" && parent === void 0,
8149
+ readResponse: access.operation === "read" && parent === void 0
7815
8150
  });
7816
8151
  const execution = Object.freeze(/* @__PURE__ */ Object.create(null));
7817
8152
  executions.set(
@@ -7865,7 +8200,10 @@ function deriveServiceExecution(receiver, parent, access, applicability = "servi
7865
8200
  relatedTargets: captured.relatedTargets,
7866
8201
  configuration: captured.configuration,
7867
8202
  requestPermissions: getAuthorizationPermissions(record3.authorization, record3.binding),
7868
- parent: record3.authorization
8203
+ parent: record3.authorization,
8204
+ // The resolver authenticates root-read provenance and the unchanged owner tuple.
8205
+ // Effective list access is still a read; write branches cannot inherit this marker.
8206
+ readResponse: record3.access.operation === "read" && access.operation === "read"
7869
8207
  });
7870
8208
  const execution = Object.freeze(/* @__PURE__ */ Object.create(null));
7871
8209
  executions.set(
@@ -8271,20 +8609,20 @@ var copyAuthorizedOutput = (value) => {
8271
8609
  transferDocumentAuthorizationGraph(value, copy);
8272
8610
  return copy;
8273
8611
  };
8274
- var isVirtualContainerValueForGuard = (value) => isPlainObject18(value) && "sub" in value;
8612
+ var isVirtualContainerValueForGuard = (value) => isPlainObject19(value) && "sub" in value;
8275
8613
  var getScopeVirtualsForGuard = (rootVirtuals, scopePath) => {
8276
- if (!rootVirtuals || !isPlainObject18(rootVirtuals)) return null;
8614
+ if (!rootVirtuals || !isPlainObject19(rootVirtuals)) return null;
8277
8615
  if (scopePath.length === 0) return rootVirtuals;
8278
8616
  let current = rootVirtuals;
8279
8617
  for (let i = 0; i < scopePath.length; i += 2) {
8280
8618
  const field = scopePath[i];
8281
8619
  const subMarker = scopePath[i + 1];
8282
8620
  if (!field || subMarker !== "sub") return null;
8283
- if (!isPlainObject18(current)) return null;
8621
+ if (!isPlainObject19(current)) return null;
8284
8622
  const container = current[field];
8285
8623
  if (!isVirtualContainerValueForGuard(container)) return null;
8286
8624
  current = container.sub;
8287
- if (!isPlainObject18(current)) return null;
8625
+ if (!isPlainObject19(current)) return null;
8288
8626
  }
8289
8627
  return current;
8290
8628
  };
@@ -8350,7 +8688,7 @@ var sanitizeSubScopeVirtualKeys = (data, snapshot, sub) => {
8350
8688
  for (const entry of value) stripScope(entry, currentScope);
8351
8689
  return;
8352
8690
  }
8353
- if (!isPlainObject18(value)) return;
8691
+ if (!isPlainObject19(value)) return;
8354
8692
  const record3 = value;
8355
8693
  const leaves = getScopeVirtualLeafNames(snapshot, currentScope);
8356
8694
  for (const leaf of leaves) {
@@ -8363,7 +8701,7 @@ var sanitizeSubScopeVirtualKeys = (data, snapshot, sub) => {
8363
8701
  for (const key of Object.keys(record3)) {
8364
8702
  if (leaves.has(key) || containers.has(key)) continue;
8365
8703
  const child = record3[key];
8366
- if (Array.isArray(child) || isPlainObject18(child)) {
8704
+ if (Array.isArray(child) || isPlainObject19(child)) {
8367
8705
  stripScope(child, currentScope);
8368
8706
  }
8369
8707
  }
@@ -8375,7 +8713,7 @@ var LOGICAL_FILTER_KEYS = /* @__PURE__ */ new Set(["$and", "$or", "$nor"]);
8375
8713
  var isOperatorKey = (key) => key.startsWith("$");
8376
8714
  var REMOVED_VIRTUAL_FILTER = /* @__PURE__ */ Symbol("removed virtual filter clause");
8377
8715
  var rewriteFilterObject = (value, visit) => {
8378
- if (!isPlainObject18(value)) return value;
8716
+ if (!isPlainObject19(value)) return value;
8379
8717
  let changed = false;
8380
8718
  const entries = [];
8381
8719
  for (const [key, child] of Object.entries(value)) {
@@ -8406,7 +8744,7 @@ var resolveVirtualFilterField = (path, scope2) => {
8406
8744
  if (!Object.hasOwn(scope2, segment) || scope2[segment] === void 0) return null;
8407
8745
  const definition = scope2[segment];
8408
8746
  if (!isVirtualContainerValueForGuard(definition)) return REMOVED_VIRTUAL_FILTER;
8409
- scope2 = isPlainObject18(definition.sub) ? definition.sub : null;
8747
+ scope2 = isPlainObject19(definition.sub) ? definition.sub : null;
8410
8748
  inContainer = true;
8411
8749
  }
8412
8750
  return scope2;
@@ -8418,7 +8756,7 @@ var stripVirtualFilterOperator = (key, value, scope2) => {
8418
8756
  }
8419
8757
  if (key === "$all") {
8420
8758
  return rewriteFilterClauses(value, (entry) => {
8421
- if (!isPlainObject18(entry) || Object.keys(entry).length !== 1 || !Object.hasOwn(entry, "$elemMatch")) return entry;
8759
+ if (!isPlainObject19(entry) || Object.keys(entry).length !== 1 || !Object.hasOwn(entry, "$elemMatch")) return entry;
8422
8760
  return rewriteFilterObject(entry, (operator, operand) => stripVirtualFilterOperator(operator, operand, scope2));
8423
8761
  });
8424
8762
  }
@@ -8433,7 +8771,7 @@ var stripVirtualFilterQuery = (value, scope2, element = false) => {
8433
8771
  if (isOperatorKey(key)) return element ? stripVirtualFilterOperator(key, child, scope2) : child;
8434
8772
  const fieldScope = resolveVirtualFilterField(key, scope2);
8435
8773
  if (fieldScope === REMOVED_VIRTUAL_FILTER) return REMOVED_VIRTUAL_FILTER;
8436
- if (!fieldScope || !isPlainObject18(child)) return child;
8774
+ if (!fieldScope || !isPlainObject19(child)) return child;
8437
8775
  if (Object.keys(child).some(isOperatorKey)) {
8438
8776
  return rewriteFilterObject(
8439
8777
  child,
@@ -8457,7 +8795,7 @@ function getCorrelatedTemplateDepth(includes) {
8457
8795
  const visit = (entries, depth) => {
8458
8796
  const list = castArray2(entries).filter(Boolean);
8459
8797
  for (const entry of list) {
8460
- if (!isPlainObject18(entry)) continue;
8798
+ if (!isPlainObject19(entry)) continue;
8461
8799
  max = Math.max(max, depth);
8462
8800
  const nested = entry.args?.include;
8463
8801
  if (nested !== void 0) {
@@ -8486,7 +8824,7 @@ function validateClientFilter(filter2) {
8486
8824
  value.forEach((item, index) => visit(item, `${path}[${index}]`));
8487
8825
  return;
8488
8826
  }
8489
- if (!isPlainObject18(value)) return;
8827
+ if (!isPlainObject19(value)) return;
8490
8828
  Object.entries(value).forEach(([key, child]) => {
8491
8829
  const nextPath = path ? `${path}.${key}` : key;
8492
8830
  if (blockedOperators.has(key)) {
@@ -8768,9 +9106,9 @@ var Base = class {
8768
9106
  const walk = (node, prefix) => {
8769
9107
  for (const [key, value] of Object.entries(node)) {
8770
9108
  if (value === void 0) continue;
8771
- if (isPlainObject18(value) && "sub" in value) {
9109
+ if (isPlainObject19(value) && "sub" in value) {
8772
9110
  const sub = value.sub;
8773
- if (isPlainObject18(sub)) walk(sub, prefix ? `${prefix}.${key}` : key);
9111
+ if (isPlainObject19(sub)) walk(sub, prefix ? `${prefix}.${key}` : key);
8774
9112
  continue;
8775
9113
  }
8776
9114
  out.push(prefix ? `${prefix}.${key}` : key);
@@ -8823,7 +9161,7 @@ var Base = class {
8823
9161
  this.throwClientRequestError("bad_request" /* BadRequest */, `Model ${modelName} not found`);
8824
9162
  }
8825
9163
  for (const entry of entries) {
8826
- if (!isPlainObject18(entry)) continue;
9164
+ if (!isPlainObject19(entry)) continue;
8827
9165
  const models = visited.get(entry) ?? /* @__PURE__ */ new Set();
8828
9166
  if (models.has(modelName)) continue;
8829
9167
  models.add(modelName);
@@ -9442,7 +9780,7 @@ import {
9442
9780
  get as get13,
9443
9781
  isArray as isArray10,
9444
9782
  isBoolean as isBoolean4,
9445
- isPlainObject as isPlainObject25,
9783
+ isPlainObject as isPlainObject26,
9446
9784
  omit,
9447
9785
  set as set10,
9448
9786
  uniq as uniq2,
@@ -9543,7 +9881,7 @@ var model_default = Model;
9543
9881
  // src/acl/distinct-field-authorization.ts
9544
9882
  init_field_authorization();
9545
9883
  init_field_catalog();
9546
- import { isPlainObject as isPlainObject19 } from "@web-ts-toolkit/utils";
9884
+ import { isPlainObject as isPlainObject20 } from "@web-ts-toolkit/utils";
9547
9885
  var schemaVariants = (schema) => Object.values(schema.discriminators ?? {});
9548
9886
  var scalarTypes = /* @__PURE__ */ new Set([
9549
9887
  "String",
@@ -9623,8 +9961,8 @@ function isDistinctFieldAuthorized(args) {
9623
9961
  if (path !== field && !path.startsWith(`${field}.`) && !field.startsWith(`${path}.`)) continue;
9624
9962
  if (path.startsWith(`${field}.`) && (!eligible(path) || !schemaShape(schema, path) || !granted(path)))
9625
9963
  return false;
9626
- if (isPlainObject19(raw) && raw.sub !== void 0) {
9627
- if (!isPlainObject19(raw.sub) || !declaredRulesSafe(raw.sub, path, next)) return false;
9964
+ if (isPlainObject20(raw) && raw.sub !== void 0) {
9965
+ if (!isPlainObject20(raw.sub) || !declaredRulesSafe(raw.sub, path, next)) return false;
9628
9966
  }
9629
9967
  }
9630
9968
  return true;
@@ -9802,7 +10140,7 @@ init_populate_target();
9802
10140
 
9803
10141
  // src/helpers/apply-update.ts
9804
10142
  init_lib();
9805
- import { isPlainObject as isPlainObject23, set as set8 } from "@web-ts-toolkit/utils";
10143
+ import { isPlainObject as isPlainObject24, set as set8 } from "@web-ts-toolkit/utils";
9806
10144
  function applyUpdate(target, data, allowedFields) {
9807
10145
  const wholeFields = /* @__PURE__ */ new Set();
9808
10146
  const partialContainers = /* @__PURE__ */ new Set();
@@ -9822,7 +10160,7 @@ function applyUpdate(target, data, allowedFields) {
9822
10160
  const apply = (values, prefix = "") => {
9823
10161
  for (const [key, value] of Object.entries(values)) {
9824
10162
  const path = prefix ? `${prefix}.${key}` : key;
9825
- if (partialContainers.has(path) && !wholeFields.has(path) && (isPlainObject23(value) || Array.isArray(value))) {
10163
+ if (partialContainers.has(path) && !wholeFields.has(path) && (isPlainObject24(value) || Array.isArray(value))) {
9826
10164
  apply(value, path);
9827
10165
  } else if (isDocument2(target)) {
9828
10166
  target.set(path, value);
@@ -9839,7 +10177,7 @@ init_document();
9839
10177
  init_request_work();
9840
10178
  init_logger_helpers();
9841
10179
  init_request_complexity();
9842
- import { get as get10, isPlainObject as isPlainObject24, set as set9 } from "@web-ts-toolkit/utils";
10180
+ import { get as get10, isPlainObject as isPlainObject25, set as set9 } from "@web-ts-toolkit/utils";
9843
10181
  import { mongo as mongo5 } from "mongoose";
9844
10182
 
9845
10183
  // src/acl/select-resolution.ts
@@ -9956,7 +10294,7 @@ init_field_catalog();
9956
10294
  init_service_authorization();
9957
10295
  var own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
9958
10296
  var inside = (path, root) => path === root || path.startsWith(`${root}.`);
9959
- var record2 = (value) => isPlainObject24(value);
10297
+ var record2 = (value) => isPlainObject25(value);
9960
10298
  function inputValue(value) {
9961
10299
  if (typeof value === "function" || typeof value === "symbol") {
9962
10300
  authorizationError("input values must be persisted data, not functions or symbols");
@@ -10854,6 +11192,11 @@ var Service = class extends Base {
10854
11192
  ["args", args],
10855
11193
  ["options", options]
10856
11194
  ]) {
11195
+ if (value !== null && (typeof value === "object" || typeof value === "function")) {
11196
+ for (const key of ["unsafeSkipListDocumentSnapshotChecks", "unsafeSkipReadDocumentSnapshotChecks"]) {
11197
+ if (key in value) authorizationError(`${slot}.${key} is server model configuration only`);
11198
+ }
11199
+ }
10857
11200
  if (value !== null && (typeof value === "object" || typeof value === "function") && "authorization" in value && (slot === "args" || !authorizationOptions)) {
10858
11201
  authorizationError(`${slot}.authorization is unsupported here; inputFields requires model mutation options`);
10859
11202
  }
@@ -11383,7 +11726,7 @@ var Service = class extends Base {
11383
11726
  if (this.isScalarPopulateValue(rawTarget)) return rawTarget;
11384
11727
  const isDoc = (() => {
11385
11728
  try {
11386
- if (isPlainObject25(rawTarget)) return true;
11729
+ if (isPlainObject26(rawTarget)) return true;
11387
11730
  const maybe = rawTarget;
11388
11731
  if (maybe && typeof maybe === "object" && "_doc" in maybe) return true;
11389
11732
  if (maybe && typeof maybe.toObject === "function") return true;
@@ -13786,7 +14129,7 @@ init_helpers();
13786
14129
 
13787
14130
  // src/processors.ts
13788
14131
  init_permissions_alias();
13789
- import { cloneDeep as cloneDeep5, forEach as forEach5, get as get14, hasOwn as hasOwn3, isArray as isArray11, isPlainObject as isPlainObject26, map, set as set11 } from "@web-ts-toolkit/utils";
14132
+ import { cloneDeep as cloneDeep5, forEach as forEach5, get as get14, hasOwn as hasOwn3, isArray as isArray11, isPlainObject as isPlainObject27, map, set as set11 } from "@web-ts-toolkit/utils";
13790
14133
  function cloneProcessorValue(value) {
13791
14134
  const copy = cloneDeep5(value);
13792
14135
  copyPermissionsAliasGraph(value, copy);
@@ -13826,7 +14169,7 @@ function resolveLeafParents(obj, src) {
13826
14169
  for (let ind = 0; ind < segs.length - 1; ind += 1) {
13827
14170
  const seg = segs[ind];
13828
14171
  targets = targets.reduce((ret, target) => {
13829
- if (!isPlainObject26(target)) return ret;
14172
+ if (!isPlainObject27(target)) return ret;
13830
14173
  const targetObject = target;
13831
14174
  const next = targetObject[seg];
13832
14175
  if (isArray11(next)) {
@@ -13840,7 +14183,7 @@ function resolveLeafParents(obj, src) {
13840
14183
  const leaf = segs[segs.length - 1];
13841
14184
  const pairs = [];
13842
14185
  forEach5(targets, (target) => {
13843
- if (!isPlainObject26(target)) return;
14186
+ if (!isPlainObject27(target)) return;
13844
14187
  pairs.push({ parent: target, leaf });
13845
14188
  });
13846
14189
  return pairs;
@@ -13861,7 +14204,7 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
13861
14204
  forEach5(segs, (seg, ind) => {
13862
14205
  if (segs.length === ind + 1) {
13863
14206
  forEach5(targets, (target) => {
13864
- if (!isPlainObject26(target)) return;
14207
+ if (!isPlainObject27(target)) return;
13865
14208
  const targetObject = target;
13866
14209
  const leaf = targetObject[seg];
13867
14210
  const sourceForDest = leaf;
@@ -13869,7 +14212,7 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
13869
14212
  if (isArray11(leaf)) {
13870
14213
  if (leaf.length === 0) {
13871
14214
  depopulated = [];
13872
- } else if (leaf.every((item) => isPlainObject26(item))) {
14215
+ } else if (leaf.every((item) => isPlainObject27(item))) {
13873
14216
  depopulated = map(leaf, idField).map((id, i) => {
13874
14217
  if (id === void 0) {
13875
14218
  failMissingId(`${src}[${i}]`);
@@ -13879,7 +14222,7 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
13879
14222
  } else {
13880
14223
  return;
13881
14224
  }
13882
- } else if (isPlainObject26(leaf)) {
14225
+ } else if (isPlainObject27(leaf)) {
13883
14226
  const id = get14(leaf, idField);
13884
14227
  if (id === void 0) {
13885
14228
  failMissingId(src);
@@ -13893,7 +14236,7 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
13893
14236
  });
13894
14237
  } else {
13895
14238
  targets = targets.reduce((ret, target) => {
13896
- if (!isPlainObject26(target)) return ret;
14239
+ if (!isPlainObject27(target)) return ret;
13897
14240
  const targetObject = target;
13898
14241
  const next = targetObject[seg];
13899
14242
  if (isArray11(next)) {
@@ -13999,7 +14342,7 @@ var countPaths = (docObject, operations, options = { mutable: true }) => {
13999
14342
  let count;
14000
14343
  if (isArray11(leafValue)) {
14001
14344
  count = leafValue.length;
14002
- } else if (isPlainObject26(leafValue)) {
14345
+ } else if (isPlainObject27(leafValue)) {
14003
14346
  count = Object.keys(leafValue).length;
14004
14347
  } else if (leafValue === null || typeof leafValue === "undefined") {
14005
14348
  count = 0;
@@ -14641,12 +14984,12 @@ function guard(condition) {
14641
14984
  const permissions = req[PERMISSIONS];
14642
14985
  let cond = condition;
14643
14986
  let phas = (key) => permissions.has(key);
14644
- if (isPlainObject27(condition)) {
14987
+ if (isPlainObject28(condition)) {
14645
14988
  const { modelName, id, condition: _cond } = condition;
14646
14989
  const svc = req.macl.getPublicService(modelName);
14647
14990
  const select = getModelOption(modelName, `alwaysSelectFields.read`, void 0);
14648
14991
  let _id = isString7(id) ? id : null;
14649
- if (isPlainObject27(id)) {
14992
+ if (isPlainObject28(id)) {
14650
14993
  const { type = "param", key } = id;
14651
14994
  if (type === "param") {
14652
14995
  const paramValue = req.params[key];
@@ -14688,7 +15031,7 @@ import express2 from "express";
14688
15031
 
14689
15032
  // src/routers/model-router.ts
14690
15033
  import JsonRouter8 from "@web-ts-toolkit/express-json-router";
14691
- import { forEach as forEach7, isPlainObject as isPlainObject29, isString as isString8, isUndefined as isUndefined2, normalizeUrlPath as normalizeUrlPath3, padEnd } from "@web-ts-toolkit/utils";
15034
+ import { forEach as forEach7, isPlainObject as isPlainObject30, isString as isString8, isUndefined as isUndefined2, normalizeUrlPath as normalizeUrlPath3, padEnd } from "@web-ts-toolkit/utils";
14692
15035
  init_logger_helpers();
14693
15036
  init_runtime();
14694
15037
  init_runtime_context();
@@ -14822,7 +15165,7 @@ import JsonRouter7 from "@web-ts-toolkit/express-json-router";
14822
15165
 
14823
15166
  // src/validation/common.ts
14824
15167
  import { z as z2 } from "zod";
14825
- import { isPlainObject as isPlainObject28 } from "@web-ts-toolkit/utils";
15168
+ import { isPlainObject as isPlainObject29 } from "@web-ts-toolkit/utils";
14826
15169
 
14827
15170
  // src/validation/public-admission-schema.ts
14828
15171
  init_public_admission();
@@ -14951,7 +15294,7 @@ var correlatedFilterSchema = z2.record(z2.string(), z2.unknown()).superRefine((f
14951
15294
  }
14952
15295
  });
14953
15296
  var correlatedEmptyOptionsSchema = z2.unknown().refine(
14954
- (value) => value === void 0 || isPlainObject28(value) && Object.keys(value).length === 0,
15297
+ (value) => value === void 0 || isPlainObject29(value) && Object.keys(value).length === 0,
14955
15298
  "Correlated include options must be absent or empty"
14956
15299
  ).optional();
14957
15300
  var correlatedPathSchema = z2.string().min(1).superRefine((path, ctx) => {
@@ -14988,7 +15331,7 @@ var correlatedListArgsSchema = z2.object({
14988
15331
  include: z2.lazy(() => correlatedNestedIncludeSchema).optional()
14989
15332
  }).strict().superRefine((args, ctx) => checkArgsMarkers(args.select, args.sort, ctx));
14990
15333
  var correlatedCountArgsSchema = z2.unknown().refine(
14991
- (value) => value === void 0 || isPlainObject28(value) && Object.keys(value).length === 0,
15334
+ (value) => value === void 0 || isPlainObject29(value) && Object.keys(value).length === 0,
14992
15335
  "Count includes accept no args"
14993
15336
  ).optional();
14994
15337
  var correlatedReadByIdSchema = z2.object({
@@ -15041,7 +15384,7 @@ var correlatedNestedIncludeSchema = z2.union([includeItemSchema, z2.array(includ
15041
15384
  var rejectDuplicateCorrelatedPaths = (items, ctx) => {
15042
15385
  const seen = /* @__PURE__ */ new Set();
15043
15386
  items.forEach((item, index) => {
15044
- if (isPlainObject28(item) && item.mode === "correlated" && typeof item.path === "string") {
15387
+ if (isPlainObject29(item) && item.mode === "correlated" && typeof item.path === "string") {
15045
15388
  if (seen.has(item.path)) {
15046
15389
  ctx.addIssue({
15047
15390
  code: z2.ZodIssueCode.custom,
@@ -17042,7 +17385,7 @@ var ModelRouter = class _ModelRouter {
17042
17385
  value
17043
17386
  );
17044
17387
  }
17045
- if (arguments.length === 1 && isPlainObject29(keyOrOptions)) {
17388
+ if (arguments.length === 1 && isPlainObject30(keyOrOptions)) {
17046
17389
  assertMutableRouterOptions("model", keyOrOptions);
17047
17390
  this.runtime.setModelOptions(
17048
17391
  this.modelName,
@@ -17576,7 +17919,7 @@ var RootRouter = class {
17576
17919
 
17577
17920
  // src/routers/data-router.ts
17578
17921
  import JsonRouter10 from "@web-ts-toolkit/express-json-router";
17579
- import { isPlainObject as isPlainObject30, isString as isString9, isUndefined as isUndefined3, normalizeUrlPath as normalizeUrlPath5 } from "@web-ts-toolkit/utils";
17922
+ import { isPlainObject as isPlainObject31, isString as isString9, isUndefined as isUndefined3, normalizeUrlPath as normalizeUrlPath5 } from "@web-ts-toolkit/utils";
17580
17923
  init_runtime();
17581
17924
  init_helpers();
17582
17925
  init_schemas();
@@ -17792,7 +18135,7 @@ var DataRouter = class {
17792
18135
  value
17793
18136
  );
17794
18137
  }
17795
- if (arguments.length === 1 && isPlainObject30(keyOrOptions)) {
18138
+ if (arguments.length === 1 && isPlainObject31(keyOrOptions)) {
17796
18139
  assertMutableRouterOptions("data", keyOrOptions);
17797
18140
  this.runtime.setDataOptions(this.dataName, keyOrOptions);
17798
18141
  }
@@ -17951,7 +18294,7 @@ function createRuntimeApi(runtime) {
17951
18294
  if (arguments.length === 2 && isString10(keyOrOptions)) {
17952
18295
  return runtime.setGlobalOption(keyOrOptions, value);
17953
18296
  }
17954
- if (arguments.length === 1 && isPlainObject31(keyOrOptions)) {
18297
+ if (arguments.length === 1 && isPlainObject32(keyOrOptions)) {
17955
18298
  return runtime.setGlobalOptions(keyOrOptions);
17956
18299
  }
17957
18300
  };