@web-ts-toolkit/access-router 0.58.0 → 0.59.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.
Files changed (3) hide show
  1. package/index.js +1155 -850
  2. package/index.mjs +1032 -728
  3. package/package.json +3 -3
package/index.mjs CHANGED
@@ -3801,11 +3801,10 @@ function readServiceOutputPolicy(call, binding) {
3801
3801
  function readServiceOutputFieldAuthorization(call, binding) {
3802
3802
  assertAuthorizationBinding(call, binding);
3803
3803
  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");
3804
+ const reusable = reusableOutputFieldConfiguration(record3);
3807
3805
  return Object.freeze({
3808
3806
  access: record3.output.access,
3807
+ catalog: record3.output.catalog,
3809
3808
  outputFields: record3.output.outputFields,
3810
3809
  reusable,
3811
3810
  ...copyAuthorizationValue(
@@ -3817,6 +3816,16 @@ function readServiceOutputFieldAuthorization(call, binding) {
3817
3816
  )
3818
3817
  });
3819
3818
  }
3819
+ function reusableOutputFieldConfiguration(record3) {
3820
+ return record3.reusableFieldConfiguration ??= hasStableConfigurationCopies(record3.configuration.permissionSchema) && // Coercion methods can observe an object's identity even without native
3821
+ // leaves. Keep those receivers local to the original resolution boundary.
3822
+ (record3.configuration.modelPermissionPrefix === null || typeof record3.configuration.modelPermissionPrefix !== "object");
3823
+ }
3824
+ function canPrepareStaticOutputPolicy(call, binding) {
3825
+ assertAuthorizationBinding(call, binding);
3826
+ const record3 = callRecord(call);
3827
+ return reusableOutputFieldConfiguration(record3) && typeof (record3.configuration.modelPermissionPrefix ?? "") === "string";
3828
+ }
3820
3829
  function getAuthorizationPermissions(call, binding) {
3821
3830
  assertAuthorizationBinding(call, binding);
3822
3831
  return callRecord(call).permissions;
@@ -3835,435 +3844,98 @@ var init_service_authorization = __esm({
3835
3844
  }
3836
3845
  });
3837
3846
 
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
- });
3847
+ // src/acl/field-authorization.ts
3848
+ function extractScopedOutputRule(schema, field, access) {
3849
+ if (!schema || !Object.prototype.hasOwnProperty.call(schema, field)) return void 0;
3850
+ const raw = schema[field];
3851
+ return raw && typeof raw === "object" && !Array.isArray(raw) && Object.prototype.hasOwnProperty.call(raw, access) ? raw[access] : raw;
3880
3852
  }
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;
3853
+ function extractOutputFieldRules(schema, path, access) {
3854
+ return extractOutputFieldRuleEntries(schema, path, access).map((entry) => entry.rule);
3886
3855
  }
3887
- function documentRecord(handle) {
3888
- const record3 = documents.get(handle);
3889
- if (!record3) authorizationError("invalid document handle");
3890
- stageRecord(record3.stage);
3891
- return record3;
3856
+ function extractOutputFieldRuleEntries(schema, path, access, prefix = "") {
3857
+ if (!schema) return [{ path: `${prefix}${path}`, rule: void 0 }];
3858
+ if (Object.prototype.hasOwnProperty.call(schema, path))
3859
+ return [{ path: `${prefix}${path}`, rule: extractScopedOutputRule(schema, path, access) }];
3860
+ const [head, ...rest] = path.split(".");
3861
+ const rule = extractScopedOutputRule(schema, head, access);
3862
+ const raw = schema[head];
3863
+ const entry = { path: `${prefix}${head}`, rule };
3864
+ if (!rest.length || !raw?.sub) return [entry];
3865
+ return [entry, ...extractOutputFieldRuleEntries(raw.sub, rest.join("."), access, `${prefix}${head}.`)];
3892
3866
  }
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;
3867
+ function hasExplicitFieldGrant(policy, path) {
3868
+ return policy?.mode === "unrestricted" || policy?.mode === "grant" && policy.paths.some((grant) => path === grant || path.startsWith(`${grant}.`));
3904
3869
  }
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
- }
3870
+ function classifyRequestFieldRule(rule, permissions, modelPermissionPrefix = "") {
3871
+ if (typeof rule === "boolean") return rule ? "granted" : "denied";
3872
+ if (typeof rule === "function") return "deferred";
3873
+ const validator = createValidator((key) => permissions.has(key));
3874
+ if (typeof rule !== "string" && !Array.isArray(rule)) return "denied";
3875
+ if (typeof rule === "string" ? validator.stringHandler(rule) : validator.arrayHandler(rule)) return "granted";
3876
+ const possible = createValidator(
3877
+ (key) => permissions.has(key) || !modelPermissionPrefix || key.startsWith(modelPermissionPrefix)
3878
+ );
3879
+ return (typeof rule === "string" ? possible.stringHandler(rule) : possible.arrayHandler(rule)) ? "deferred" : "denied";
3911
3880
  }
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;
3881
+ function prepareRequestFieldRule(rule, permissions, modelPermissionPrefix = "") {
3882
+ const state = classifyRequestFieldRule(rule, permissions, modelPermissionPrefix);
3883
+ const invariant = state === "denied" && modelPermissionPrefix ? classifyRequestFieldRule(rule, permissions) : state;
3884
+ return Object.freeze({ state, decision: invariant === "deferred" ? void 0 : invariant === "granted" });
3931
3885
  }
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
- });
3886
+ function combineFieldAuthorizationStates(states2) {
3887
+ return states2.includes("denied") ? "denied" : states2.includes("deferred") ? "deferred" : "granted";
3942
3888
  }
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
- });
3889
+ function classifyEffectiveFieldAuthorization(args) {
3890
+ if (hasExplicitFieldGrant(args.outputFields, args.path)) return "granted";
3891
+ const states2 = args.rules.map(
3892
+ (rule) => classifyRequestFieldRule(rule, args.globalPermissions, args.modelPermissionPrefix)
3893
+ );
3894
+ return combineFieldAuthorizationStates(states2);
3951
3895
  }
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);
3896
+ async function evaluateScopedAccessRule(args) {
3897
+ const { req, rule, globalPermissions, docPermissions, modelPermissionPrefix } = args;
3898
+ if (typeof rule === "boolean") return rule;
3899
+ const validator = createValidator((key) => {
3900
+ try {
3901
+ if (globalPermissions?.has(key)) return true;
3902
+ } catch {
3903
+ }
3904
+ try {
3905
+ return Boolean((docPermissions ?? {})[stripModelPermissionPrefix(key, modelPermissionPrefix)]);
3906
+ } catch {
3907
+ return false;
3908
+ }
3909
+ });
3910
+ if (typeof rule === "string") return validator.stringHandler(rule);
3911
+ if (Array.isArray(rule)) return validator.arrayHandler(rule);
3912
+ if (typeof rule === "function") {
3913
+ try {
3914
+ return Boolean(await rule.call(req, globalPermissions, docPermissions));
3915
+ } catch {
3916
+ return false;
3917
+ }
3978
3918
  }
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]);
3919
+ return false;
3985
3920
  }
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");
3921
+ async function evaluateEffectiveFieldAuthorization(args) {
3922
+ if (hasExplicitFieldGrant(args.outputFields, args.path)) return true;
3923
+ for (const [index, rule] of args.rules.entries()) {
3924
+ if (!await (args.evaluateRule ? args.evaluateRule(rule, index) : evaluateScopedAccessRule({ ...args, rule })))
3925
+ return false;
3996
3926
  }
3927
+ return true;
3997
3928
  }
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;
3929
+ var stripModelPermissionPrefix;
3930
+ var init_field_authorization = __esm({
3931
+ "src/acl/field-authorization.ts"() {
3932
+ init_helpers();
3933
+ stripModelPermissionPrefix = (key, prefix) => prefix && key.startsWith(prefix) ? key.slice(prefix.length) : key;
4262
3934
  }
4263
3935
  });
4264
3936
 
4265
3937
  // src/acl/virtual-projection.ts
4266
- import { get as get6, isArray as isArray7, isPlainObject as isPlainObject16 } from "@web-ts-toolkit/utils";
3938
+ import { get as get6, isArray as isArray6, isPlainObject as isPlainObject15 } from "@web-ts-toolkit/utils";
4267
3939
  function planVirtualProjection(args) {
4268
3940
  if (args.snapshot.catalog) return planCatalogProjection(args);
4269
3941
  const {
@@ -4497,20 +4169,20 @@ var init_virtual_projection = __esm({
4497
4169
  init_virtual_populate_dependencies();
4498
4170
  init_virtual_descriptor();
4499
4171
  getScopedPermissionSchema = (root, scopePath) => {
4500
- if (!root || !isPlainObject16(root)) return null;
4172
+ if (!root || !isPlainObject15(root)) return null;
4501
4173
  if (scopePath.length === 0) return root;
4502
4174
  const scoped = get6(root, scopePath.join("."));
4503
- return isPlainObject16(scoped) ? scoped : null;
4175
+ return isPlainObject15(scoped) ? scoped : null;
4504
4176
  };
4505
4177
  resolveAlwaysSelectForAccess = (raw, access) => {
4506
4178
  if (!raw) return [];
4507
- if (isArray7(raw)) return [...raw];
4508
- if (isPlainObject16(raw)) {
4179
+ if (isArray6(raw)) return [...raw];
4180
+ if (isPlainObject15(raw)) {
4509
4181
  const record3 = raw;
4510
4182
  const exact = record3[access];
4511
- if (isArray7(exact)) return [...exact];
4183
+ if (isArray6(exact)) return [...exact];
4512
4184
  const def = record3.default;
4513
- if (isArray7(def)) return [...def];
4185
+ if (isArray6(def)) return [...def];
4514
4186
  return [];
4515
4187
  }
4516
4188
  return [];
@@ -4535,6 +4207,35 @@ var init_virtual_projection = __esm({
4535
4207
  });
4536
4208
 
4537
4209
  // src/acl/output-projection.ts
4210
+ import { types as types2 } from "util";
4211
+ function copyOutputDecisionFields(value) {
4212
+ if (!Array.isArray(value) || types2.isProxy(value) || Object.getPrototypeOf(value) !== Array.prototype) return;
4213
+ const length = Object.getOwnPropertyDescriptor(value, "length").value;
4214
+ if (length > 2e4) return;
4215
+ const fields = [];
4216
+ for (let index = 0; index < length; index++) {
4217
+ const slot = Object.getOwnPropertyDescriptor(value, String(index));
4218
+ if (!slot || !("value" in slot) || typeof slot.value !== "string") return;
4219
+ fields.push(slot.value);
4220
+ }
4221
+ return Object.freeze(fields);
4222
+ }
4223
+ function readStaticOutputPlanFields(plan, authorization) {
4224
+ const record3 = staticPlanFields.get(plan);
4225
+ if (!record3 || record3.authorization !== authorization || types2.isProxy(plan)) return;
4226
+ const ownValue2 = (key) => {
4227
+ const slot = Object.getOwnPropertyDescriptor(plan, key);
4228
+ return slot && "value" in slot ? slot.value : void 0;
4229
+ };
4230
+ if (ownValue2("authorization") !== authorization || ownValue2("authorizationBinding") !== record3.binding) return;
4231
+ const children = ownValue2("childPlans");
4232
+ if (children !== record3.children || types2.isProxy(children) || Reflect.ownKeys(children).length) return;
4233
+ const persisted = copyOutputDecisionFields(ownValue2("outputPersistedFields"));
4234
+ const virtuals = copyOutputDecisionFields(ownValue2("outputVirtualNames"));
4235
+ const same = (a, b) => a?.length === b.length && a.every((field, index) => field === b[index]);
4236
+ if (!same(persisted, record3.persisted) || !same(virtuals, record3.virtuals)) return;
4237
+ return Object.freeze([.../* @__PURE__ */ new Set([...record3.persisted, ...record3.virtuals])]);
4238
+ }
4538
4239
  function compactPersistedProjection(paths) {
4539
4240
  const unique = [...new Set(paths.filter((p) => p && !p.startsWith("-")))];
4540
4241
  return unique.filter((path) => !unique.some((parent) => parent !== path && path.startsWith(`${parent}.`)));
@@ -4563,6 +4264,13 @@ function planAuthorizedModelProjection(args) {
4563
4264
  );
4564
4265
  plan.authorization = args.authorization;
4565
4266
  plan.authorizationBinding = Object.freeze({ ...args.binding, scopePath: Object.freeze(scope2) });
4267
+ staticPlanFields.set(plan, {
4268
+ authorization: args.authorization,
4269
+ binding: plan.authorizationBinding,
4270
+ persisted: Object.freeze([...plan.outputPersistedFields]),
4271
+ virtuals: Object.freeze([...plan.outputVirtualNames]),
4272
+ children: plan.childPlans
4273
+ });
4566
4274
  return plan;
4567
4275
  }
4568
4276
  function planCatalogProjection(args, outputFields = { mode: "request" }) {
@@ -4660,116 +4368,755 @@ function planCatalogProjection(args, outputFields = { mode: "request" }) {
4660
4368
  outputAccess
4661
4369
  });
4662
4370
  }
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("."));
4371
+ const ancestors = /* @__PURE__ */ new Set();
4372
+ for (const path of [...persisted, ...allVirtuals]) {
4373
+ const parts = path.split(".");
4374
+ for (let i = 1; i < parts.length; i++) ancestors.add(parts.slice(0, i).join("."));
4375
+ }
4376
+ const children = {};
4377
+ for (const name of [...ancestors].filter((p) => !p.includes("."))) {
4378
+ const childIncludes = includes.filter((p) => p.startsWith(`${name}.`)).map((p) => p.slice(name.length + 1));
4379
+ const childExcludes = excludes.filter((p) => p.startsWith(`${name}.`)).map((p) => `-${p.slice(name.length + 1)}`);
4380
+ const childSelect = mode === "include" && !includes.includes(name) ? [...childIncludes, ...childExcludes] : childExcludes;
4381
+ children[name] = planCatalogProjection(
4382
+ {
4383
+ ...args,
4384
+ scopePath: [...args.scopePath ?? [], name, "sub"],
4385
+ requestedSelect: childSelect,
4386
+ effectiveSelect: childSelect,
4387
+ related: [],
4388
+ internalFetch: { baseFields: [] }
4389
+ },
4390
+ outputFields
4391
+ );
4392
+ }
4393
+ const internal = args.internalFetch ?? {};
4394
+ const fetchIdRetained = scope2.length === 0 || catalog.paths.includes(full("_id")) || !!catalog.dynamicPaths?.some((p) => p.endsWith("._id") && matchesCatalogPattern(p, full("_id")));
4395
+ const identity = fetchIdRetained ? ["_id"] : [];
4396
+ const always = scope2.length ? [] : [
4397
+ .../* @__PURE__ */ new Set([
4398
+ ...resolveAlwaysSelectForAccess(snapshot.alwaysSelectFields, outputAccess),
4399
+ ...resolveAlwaysSelectForAccess(snapshot.alwaysSelectFields, docPermissionsAccess)
4400
+ ])
4401
+ ];
4402
+ const joins = [...internal.joinFields ?? [], ...internal.extraPersistedFields ?? []];
4403
+ const forced = [...always, ...joins, ...internal.baseFields ?? identity, ...internal.identityFields ?? []];
4404
+ const fetchSafe = (path) => isSafeOutputPath(path) && !virtual(full(path));
4405
+ const dependencies = Object.keys(depProvenance).filter(fetchSafe);
4406
+ const childFetch = Object.entries(children).flatMap(([name, child]) => {
4407
+ if (child.persistedFetchSelection.length) return child.persistedFetchSelection.map((p) => `${name}.${p}`);
4408
+ depProvenance[name] = allVirtuals.filter((p) => p.startsWith(`${name}.`));
4409
+ return [name];
4410
+ });
4411
+ const publicChildFetch = Object.entries(children).flatMap(
4412
+ ([name, child]) => child.publicPersistedFetchSelection.length ? child.publicPersistedFetchSelection.map((path) => `${name}.${path}`) : [name]
4413
+ );
4414
+ const publicPersistedFetchSelection = compactPersistedProjection([
4415
+ ...persisted,
4416
+ ...dependencies,
4417
+ ...forced.filter(fetchSafe),
4418
+ ...identity,
4419
+ ...publicChildFetch
4420
+ ]);
4421
+ const publicStructurePaths = Object.entries(children).flatMap(([name, child]) => {
4422
+ if ([...persisted, ...dependencies, ...forced].some((path) => name === path || name.startsWith(`${path}.`)))
4423
+ return [];
4424
+ return child.publicPersistedFetchSelection.length ? (child.publicStructurePaths ?? []).map((path) => `${name}.${path}`) : [name];
4425
+ });
4426
+ const populateRefs = candidates.flatMap((candidate) => candidate.populateDependencies.map((dep) => dep.path));
4427
+ const privateFields = [...dependencies, ...populateRefs, ...forced.filter(fetchSafe), ...identity, ...childFetch];
4428
+ const fetch = compactPersistedProjection([...persisted, ...privateFields]);
4429
+ const outputIdExcluded = excludes.includes("_id");
4430
+ const coveredOutput = (path) => persisted.some((p) => p === path || path.startsWith(`${p}.`));
4431
+ const outputPersisted = [.../* @__PURE__ */ new Set([...persisted.filter((p) => !p.includes(".")), ...Object.keys(children)])];
4432
+ return {
4433
+ receivingModelName,
4434
+ scopePath: [...args.scopePath ?? []],
4435
+ responseScopePath: Object.freeze(scope2),
4436
+ virtualAccess,
4437
+ outputAccess,
4438
+ docPermissionsAccess,
4439
+ selectionMode: mode,
4440
+ effectiveSelectNorm: normalized,
4441
+ outputPersistedFields: outputPersisted,
4442
+ outputVirtualNames: candidates.map((c) => c.name),
4443
+ outputSelection: [...outputPersisted, ...candidates.map((c) => c.name), ...outputIdExcluded ? ["-_id"] : []],
4444
+ fieldStates: Object.freeze(states2),
4445
+ minimalAncestorPaths: Object.freeze([...ancestors]),
4446
+ persistedFetchSelection: fetch,
4447
+ publicPersistedFetchSelection,
4448
+ publicStructurePaths,
4449
+ candidates,
4450
+ depProvenance,
4451
+ virtualOnlyDeps: Object.keys(depProvenance).filter((p) => fetchSafe(p) && !coveredOutput(p)),
4452
+ internalOnlyFields: [
4453
+ ...new Set(privateFields.filter((p) => !coveredOutput(p) && (p !== "_id" || outputIdExcluded)))
4454
+ ],
4455
+ outputIdExcluded,
4456
+ fetchIdRetained,
4457
+ internalIdentityFields: identity,
4458
+ internalJoinFields: [...new Set(joins)],
4459
+ childPlans: children,
4460
+ // A parent never supplies its authority to a target; related execution will
4461
+ // call planAuthorizedModelProjection with the independently derived owner.
4462
+ relatedPlans: (args.related ?? []).map(
4463
+ (rel) => planVirtualProjection({
4464
+ ...rel,
4465
+ receivingModelName: rel.targetModelName,
4466
+ snapshot: rel.targetSnapshot,
4467
+ globalPermissions
4468
+ })
4469
+ )
4470
+ };
4471
+ }
4472
+ var staticPlanFields;
4473
+ var init_output_projection = __esm({
4474
+ "src/acl/output-projection.ts"() {
4475
+ init_query();
4476
+ init_authorization_snapshot();
4477
+ init_field_catalog();
4478
+ init_field_authorization();
4479
+ init_virtual_populate_dependencies();
4480
+ init_service_authorization();
4481
+ init_virtual_projection();
4482
+ staticPlanFields = /* @__PURE__ */ new WeakMap();
4483
+ }
4484
+ });
4485
+
4486
+ // src/acl/output-field-policy.ts
4487
+ import { types as types3 } from "util";
4488
+ import { isPlainObject as isPlainObject16 } from "@web-ts-toolkit/utils";
4489
+ function callFieldPolicy(authorization, binding) {
4490
+ assertAuthorizationBinding(authorization, binding);
4491
+ let policy = fieldPolicies.get(authorization);
4492
+ if (!policy) {
4493
+ const view = readServiceOutputFieldAuthorization(authorization, binding);
4494
+ policy = {
4495
+ schema: view.permissionSchema,
4496
+ requestPaths: view.permissionSchema == null || isPlainObject16(view.permissionSchema) && Object.isFrozen(view.permissionSchema) ? Object.freeze(Object.keys(view.permissionSchema ?? {})) : void 0,
4497
+ prefix: view.modelPermissionPrefix ?? "",
4498
+ outputFields: view.outputFields,
4499
+ catalog: view.catalog,
4500
+ reusable: view.reusable,
4501
+ accesses: /* @__PURE__ */ new Map()
4502
+ };
4503
+ if (view.reusable) fieldPolicies.set(authorization, policy);
4504
+ }
4505
+ return policy;
4506
+ }
4507
+ function requestRuleClassification(entry, authorization, permissions, prefix) {
4508
+ if (typeof prefix !== "string") return void 0;
4509
+ let classification = entry.classifications.get(authorization);
4510
+ if (!classification) {
4511
+ classification = prepareRequestFieldRule(entry.rule, permissions, prefix);
4512
+ entry.classifications.set(authorization, classification);
4513
+ }
4514
+ return classification;
4515
+ }
4516
+ function invariantRuleLookup(schema, path) {
4517
+ if (schema == null) return true;
4518
+ if (!isPlainObject16(schema) || !Object.isFrozen(schema)) return false;
4519
+ const exact = Object.getOwnPropertyDescriptor(schema, path);
4520
+ if (exact) {
4521
+ const raw2 = exact.value;
4522
+ return !raw2 || typeof raw2 !== "object" || Array.isArray(raw2) || isPlainObject16(raw2) && Object.isFrozen(raw2);
4523
+ }
4524
+ const [head, ...rest] = path.split(".");
4525
+ const raw = Object.getOwnPropertyDescriptor(schema, head)?.value;
4526
+ if (raw == null) return true;
4527
+ if (!isPlainObject16(raw) || !Object.isFrozen(raw)) return false;
4528
+ const sub = Object.getOwnPropertyDescriptor(raw, "sub");
4529
+ return !rest.length || !sub || invariantRuleLookup(sub.value, rest.join("."));
4530
+ }
4531
+ function prepareOutputPath(policy, authorization, binding, path, access) {
4532
+ let cache = policy.accesses.get(access);
4533
+ if (!cache) {
4534
+ cache = /* @__PURE__ */ new Map();
4535
+ policy.accesses.set(access, cache);
4536
+ }
4537
+ let prepared = cache.get(path);
4538
+ if (!prepared) {
4539
+ const invariant = invariantRuleLookup(policy.schema, path);
4540
+ const permissions = getAuthorizationPermissions(authorization, binding);
4541
+ const entries = extractOutputFieldRuleEntries(policy.schema, path, access).map((entry) => ({
4542
+ ...entry,
4543
+ classifications: /* @__PURE__ */ new WeakMap()
4544
+ }));
4545
+ const classifications = entries.map(
4546
+ (entry) => requestRuleClassification(entry, authorization, permissions, policy.prefix)
4547
+ );
4548
+ const backendGrant = hasExplicitFieldGrant(policy.outputFields, path);
4549
+ prepared = {
4550
+ entries,
4551
+ backendGrant,
4552
+ state: backendGrant ? "granted" : classifications.every((value) => value !== void 0) ? combineFieldAuthorizationStates(classifications.map((value) => value.state)) : void 0
4553
+ };
4554
+ if (invariant) cache.set(path, prepared);
4555
+ }
4556
+ return prepared;
4557
+ }
4558
+ function ordinaryContainer(value) {
4559
+ return value !== null && typeof value === "object" && !types3.isProxy(value) && Object.getPrototypeOf(value) === Object.prototype && Object.isFrozen(value);
4560
+ }
4561
+ function booleanRuleLookup(schema, path, access) {
4562
+ if (schema == null) return true;
4563
+ if (!ordinaryContainer(schema)) return false;
4564
+ const booleanRule = (raw) => {
4565
+ if (typeof raw === "boolean" || raw === void 0) return true;
4566
+ if (!ordinaryContainer(raw)) return false;
4567
+ const slot2 = Object.getOwnPropertyDescriptor(raw, access);
4568
+ return !!slot2 && "value" in slot2 && (typeof slot2.value === "boolean" || slot2.value === void 0);
4569
+ };
4570
+ const exact = Object.getOwnPropertyDescriptor(schema, path);
4571
+ if (exact) return "value" in exact && booleanRule(exact.value);
4572
+ const [head, ...rest] = path.split(".");
4573
+ const slot = Object.getOwnPropertyDescriptor(schema, head);
4574
+ if (!slot) return !(head in schema);
4575
+ if (!("value" in slot) || !booleanRule(slot.value)) return false;
4576
+ if (!rest.length || slot.value == null) return true;
4577
+ if (!ordinaryContainer(slot.value)) return false;
4578
+ const sub = Object.getOwnPropertyDescriptor(slot.value, "sub");
4579
+ if (!sub) return !("sub" in slot.value);
4580
+ if (!("value" in sub)) return false;
4581
+ return !sub.value || booleanRuleLookup(sub.value, rest.join("."), access);
4582
+ }
4583
+ function staticFieldPolicy(authorization, binding) {
4584
+ return canPrepareStaticOutputPolicy(authorization, binding) ? callFieldPolicy(authorization, binding) : void 0;
4585
+ }
4586
+ function prepareStaticOutputPaths(authorization, binding, paths, access, requestOnly = false) {
4587
+ const policy = staticFieldPolicy(authorization, binding);
4588
+ if (!policy?.reusable || typeof policy.prefix !== "string") return void 0;
4589
+ const { catalog } = policy;
4590
+ if (paths.some(
4591
+ (path) => !requestOnly && !isCatalogOutputPath(catalog, path) || !booleanRuleLookup(policy.schema, path, access)
4592
+ ))
4593
+ return void 0;
4594
+ return paths.map((path) => {
4595
+ const prepared = prepareOutputPath(policy, authorization, binding, path, access);
4596
+ return {
4597
+ path,
4598
+ backendGrant: !requestOnly && prepared.backendGrant,
4599
+ granted: prepared.backendGrant || prepared.entries.every((entry) => entry.rule === true),
4600
+ entries: prepared.entries.map((entry) => ({
4601
+ key: `request:${access}:${entry.path}`,
4602
+ allowed: entry.rule === true
4603
+ }))
4604
+ };
4605
+ });
4606
+ }
4607
+ var fieldPolicies;
4608
+ var init_output_field_policy = __esm({
4609
+ "src/acl/output-field-policy.ts"() {
4610
+ init_service_authorization();
4611
+ init_field_authorization();
4612
+ init_field_catalog();
4613
+ fieldPolicies = /* @__PURE__ */ new WeakMap();
4614
+ }
4615
+ });
4616
+
4617
+ // src/acl/document-authorization.ts
4618
+ import { types as types4 } from "util";
4619
+ import { Document as Document3 } from "mongoose";
4620
+ function bindOutputDocumentOwner(handle, knownOutput, owner, binding) {
4621
+ lookupDocumentOwner(handle);
4622
+ if (knownOutput || owner && unresolvedDocuments.has(owner)) unresolvedDocuments.add(handle);
4623
+ if (owner) {
4624
+ lookupDocumentOwner(owner);
4625
+ owningDocuments.set(handle, { handle: owner, binding });
4626
+ }
4627
+ }
4628
+ function readOutputDocumentOwner(handle) {
4629
+ return owningDocuments.get(handle);
4630
+ }
4631
+ function isUnresolvedOutputDocument(handle) {
4632
+ return unresolvedDocuments.has(handle);
4633
+ }
4634
+ function normalizeOutputAuthorizationOptions(input, options, purpose) {
4635
+ const value = authorizationRecord(options, "output options");
4636
+ for (const key of Reflect.ownKeys(value)) {
4637
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
4638
+ if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable) {
4639
+ authorizationError("invalid output option property");
4640
+ }
4641
+ }
4642
+ assertAuthorizationKeys(
4643
+ value,
4644
+ ["authorization", "scopePath", "documentAuthorization", ...purpose ? ["purpose"] : []],
4645
+ "output options"
4646
+ );
4647
+ if (purpose && value.purpose !== purpose) authorizationError("genAllowedFields requires purpose: output");
4648
+ if (Object.prototype.hasOwnProperty.call(value, "documentAuthorization")) {
4649
+ if (Object.prototype.hasOwnProperty.call(value, "authorization") || Object.prototype.hasOwnProperty.call(value, "scopePath")) {
4650
+ authorizationError("document handle cannot be mixed with raw policy/scope");
4651
+ }
4652
+ const handle = value.documentAuthorization;
4653
+ const { stage } = validateDocumentOwner(handle);
4654
+ const binding = Object.freeze({ ...input.binding, scopePath: stage.binding.scopePath });
4655
+ assertAuthorizationBinding(stage.call, binding);
4656
+ const access = readServiceAuthorizationAccess(stage.call, binding);
4657
+ if (input.access.outputAccess !== access.outputAccess) authorizationError("document access mismatch");
4658
+ return Object.freeze({ kind: "document", documentAuthorization: handle, binding });
4659
+ }
4660
+ if (value.scopePath !== void 0 && !Array.isArray(value.scopePath))
4661
+ authorizationError("scopePath must be an array");
4662
+ return Object.freeze({
4663
+ kind: "policy",
4664
+ authorization: resolveServiceAuthorization({
4665
+ ...input,
4666
+ binding: {
4667
+ ...input.binding,
4668
+ scopePath: copyAuthorizationValue(value.scopePath)
4669
+ },
4670
+ authorization: value.authorization,
4671
+ applicability: "output"
4672
+ })
4673
+ });
4674
+ }
4675
+ function lookupStageOwner(stage) {
4676
+ const record3 = stages.get(stage);
4677
+ if (!record3) authorizationError("invalid document stage");
4678
+ return record3;
4679
+ }
4680
+ function lookupDocumentOwner(handle) {
4681
+ const record3 = documents.get(handle);
4682
+ if (!record3) authorizationError("invalid document handle");
4683
+ return record3;
4684
+ }
4685
+ function validateStageOwner(record3) {
4686
+ if (!matchesAuthorizationSnapshot(record3.input, record3.snapshot)) authorizationError("changed document snapshot");
4687
+ }
4688
+ function validateDocumentOwner(handle) {
4689
+ const document = lookupDocumentOwner(handle);
4690
+ const stage = lookupStageOwner(document.stage);
4691
+ validateStageOwner(stage);
4692
+ validateStageOwner(stage);
4693
+ return { document, stage };
4694
+ }
4695
+ function createDocumentAuthorizationStage(call, binding, projectedSnapshot) {
4696
+ assertAuthorizationBinding(call, binding);
4697
+ authorizationRecord(projectedSnapshot, "projected document snapshot");
4698
+ const stage = Object.freeze(/* @__PURE__ */ Object.create(null));
4699
+ const ownedBinding = Object.freeze({ ...binding, scopePath: Object.freeze([...binding.scopePath ?? []]) });
4700
+ const snapshot = copyAuthorizationValue(projectedSnapshot, "document");
4701
+ stages.set(stage, {
4702
+ call,
4703
+ binding: ownedBinding,
4704
+ input: projectedSnapshot,
4705
+ snapshot
4706
+ });
4707
+ return stage;
4708
+ }
4709
+ function assertDocumentAuthorizationStage(stage, call, binding, projectedSnapshot) {
4710
+ const record3 = lookupStageOwner(stage);
4711
+ validateStageOwner(record3);
4712
+ assertAuthorizationBinding(record3.call, binding);
4713
+ if (record3.call !== call || record3.input !== projectedSnapshot || !matchesAuthorizationSnapshot(projectedSnapshot, record3.snapshot)) {
4714
+ authorizationError("document call/stage/snapshot mismatch");
4715
+ }
4716
+ }
4717
+ function resolveDocumentAuthorization(stage, resolveGrants) {
4718
+ const record3 = lookupStageOwner(stage);
4719
+ validateStageOwner(record3);
4720
+ if (!record3.result) {
4721
+ record3.result = Promise.resolve().then(async () => {
4722
+ validateStageOwner(record3);
4723
+ const result2 = resolveGrants.call(
4724
+ record3.binding.request,
4725
+ copyAuthorizationValue(record3.snapshot, "document"),
4726
+ getAuthorizationPermissions(record3.call, record3.binding)
4727
+ );
4728
+ const grants = result2 && typeof result2.then === "function" ? await result2 : result2;
4729
+ validateStageOwner(record3);
4730
+ const ownedGrants = copyAuthorizationValue(authorizationRecord(grants, "document grants"));
4731
+ const handle = Object.freeze(/* @__PURE__ */ Object.create(null));
4732
+ documents.set(handle, { stage, grants: ownedGrants, decisions: /* @__PURE__ */ new Map() });
4733
+ return handle;
4734
+ });
4735
+ }
4736
+ return record3.result;
4737
+ }
4738
+ function readDocumentAuthorization(handle, binding) {
4739
+ const { document: record3, stage } = validateDocumentOwner(handle);
4740
+ assertAuthorizationBinding(stage.call, binding);
4741
+ return Object.freeze({
4742
+ authorization: stage.call,
4743
+ stage: record3.stage,
4744
+ grants: copyAuthorizationValue(record3.grants),
4745
+ ...readServiceAuthorizationAccess(stage.call, binding)
4746
+ });
4747
+ }
4748
+ function readDocumentAuthorizationAccess(handle, binding) {
4749
+ const { document: record3, stage } = validateDocumentOwner(handle);
4750
+ return Object.freeze({
4751
+ authorization: stage.call,
4752
+ stage: record3.stage,
4753
+ ...readServiceAuthorizationAccess(stage.call, binding)
4754
+ });
4755
+ }
4756
+ function memoizeDocumentFieldDecision(handle, binding, field, evaluate) {
4757
+ const { document: record3, stage } = validateDocumentOwner(handle);
4758
+ assertAuthorizationBinding(stage.call, binding);
4759
+ let decision = record3.decisions.get(field);
4760
+ if (decision) {
4761
+ return decision.promise.then((result2) => {
4762
+ validateStageOwner(stage);
4763
+ assertAuthorizationBinding(stage.call, binding);
4764
+ return result2;
4765
+ });
4766
+ } else {
4767
+ const created = {
4768
+ state: "pending",
4769
+ promise: Promise.resolve().then(async () => {
4770
+ validateStageOwner(stage);
4771
+ assertAuthorizationBinding(stage.call, binding);
4772
+ const result2 = await evaluate.call(
4773
+ stage.binding.request,
4774
+ getAuthorizationPermissions(stage.call, binding),
4775
+ copyAuthorizationValue(record3.grants)
4776
+ );
4777
+ validateStageOwner(stage);
4778
+ assertAuthorizationBinding(stage.call, binding);
4779
+ if (typeof result2 !== "boolean") authorizationError("field decision must be boolean");
4780
+ return result2;
4781
+ })
4782
+ };
4783
+ void created.promise.then(
4784
+ (value) => {
4785
+ created.value = value;
4786
+ created.state = "fulfilled";
4787
+ },
4788
+ () => {
4789
+ created.state = "rejected";
4790
+ }
4791
+ );
4792
+ decision = created;
4793
+ record3.decisions.set(field, decision);
4794
+ }
4795
+ return decision.promise;
4796
+ }
4797
+ function ordinaryDecisionBinding(binding) {
4798
+ if (types4.isProxy(binding) || Object.getPrototypeOf(binding) !== Object.prototype) return false;
4799
+ for (const key of ["request", "runtime", "model", "modelName", "scopePath"]) {
4800
+ const slot = Object.getOwnPropertyDescriptor(binding, key);
4801
+ if (slot && !("value" in slot)) return false;
4802
+ if (!slot && key !== "scopePath") return false;
4803
+ if (!slot && key in binding) return false;
4804
+ }
4805
+ const scope2 = Object.getOwnPropertyDescriptor(binding, "scopePath")?.value;
4806
+ return scope2 === void 0 || copyOutputDecisionFields(scope2) !== void 0;
4807
+ }
4808
+ function settleStaticFieldBatch(handle, binding, paths) {
4809
+ const { document, stage } = validateDocumentOwner(handle);
4810
+ if (!ordinaryDecisionBinding(binding)) {
4811
+ validateDocumentOwner(handle);
4812
+ return;
4813
+ }
4814
+ assertAuthorizationBinding(stage.call, binding);
4815
+ const expected = /* @__PURE__ */ new Map();
4816
+ const journal = /* @__PURE__ */ new Map();
4817
+ const result2 = /* @__PURE__ */ new Map();
4818
+ const unresolved = unresolvedDocuments.has(handle);
4819
+ let available = !owningDocuments.has(handle);
4820
+ const read = (key) => {
4821
+ const memo = document.decisions.get(key);
4822
+ expected.set(key, memo);
4823
+ if (memo) {
4824
+ if (memo.state !== "fulfilled") available = false;
4825
+ return memo.value;
4826
+ }
4827
+ return journal.get(key);
4828
+ };
4829
+ for (const path of paths) {
4830
+ if (!available) break;
4831
+ let allowed = path.outputKey ? read(path.outputKey) : void 0;
4832
+ if (!available) break;
4833
+ if (allowed === void 0) {
4834
+ const policy = path.policy;
4835
+ if (!policy) {
4836
+ available = false;
4837
+ break;
4838
+ }
4839
+ if (path.outputKey && unresolved && !policy.granted) allowed = false;
4840
+ else if (path.outputKey && policy.backendGrant) allowed = true;
4841
+ else {
4842
+ allowed = true;
4843
+ for (const entry of policy.entries) {
4844
+ let decision = read(entry.key);
4845
+ if (!available) break;
4846
+ if (decision === void 0) {
4847
+ decision = entry.allowed;
4848
+ journal.set(entry.key, decision);
4849
+ }
4850
+ if (!decision) {
4851
+ allowed = false;
4852
+ break;
4853
+ }
4854
+ }
4855
+ }
4856
+ if (!available) break;
4857
+ if (path.outputKey) journal.set(path.outputKey, allowed);
4858
+ }
4859
+ result2.set(path.field, allowed);
4860
+ }
4861
+ validateDocumentOwner(handle);
4862
+ if (!ordinaryDecisionBinding(binding)) return;
4863
+ assertAuthorizationBinding(stage.call, binding);
4864
+ if (!available || owningDocuments.has(handle) || unresolvedDocuments.has(handle) !== unresolved || [...expected].some(([key, memo]) => document.decisions.get(key) !== memo))
4865
+ return;
4866
+ for (const [key, value] of journal) {
4867
+ document.decisions.set(key, { promise: Promise.resolve(value), state: "fulfilled", value });
4868
+ }
4869
+ return result2;
4870
+ }
4871
+ function tryStaticOutputFieldDecisions(handle, binding, plan, fields) {
4872
+ const document = lookupDocumentOwner(handle);
4873
+ const stage = lookupStageOwner(document.stage);
4874
+ if (!ordinaryDecisionBinding(binding) || owningDocuments.has(handle)) return;
4875
+ assertAuthorizationBinding(stage.call, binding);
4876
+ const canonical = readStaticOutputPlanFields(plan, stage.call);
4877
+ const ownedFields = copyOutputDecisionFields(fields);
4878
+ if (!canonical || !ownedFields) return;
4879
+ let index = 0;
4880
+ for (const field of ownedFields) {
4881
+ const next = canonical.indexOf(field, index);
4882
+ if (next < 0) return;
4883
+ index = next + 1;
4884
+ }
4885
+ const prefix = (binding.scopePath ?? []).join(".");
4886
+ const paths = ownedFields.map((field) => {
4887
+ const path = prefix ? `${prefix}.${field}` : field;
4888
+ return { field, path, outputKey: `output:${path}` };
4889
+ });
4890
+ const missing = [];
4891
+ for (const path of paths) {
4892
+ const memo = document.decisions.get(path.outputKey);
4893
+ if (memo && memo.state !== "fulfilled") return;
4894
+ if (!memo) missing.push(path.path);
4895
+ }
4896
+ const access = readServiceAuthorizationAccess(stage.call, binding).outputAccess;
4897
+ const prepared = missing.length ? prepareStaticOutputPaths(stage.call, binding, missing, access) : [];
4898
+ if (!prepared) return;
4899
+ const policies = new Map(prepared.map((policy) => [policy.path, policy]));
4900
+ const decisions = settleStaticFieldBatch(
4901
+ handle,
4902
+ binding,
4903
+ paths.map((path) => ({ ...path, policy: policies.get(path.path) }))
4904
+ );
4905
+ if (decisions && !readStaticOutputPlanFields(plan, stage.call)) authorizationError("changed static output plan");
4906
+ return decisions;
4907
+ }
4908
+ function tryStaticRequestFieldPaths(handle, binding, access) {
4909
+ const document = lookupDocumentOwner(handle);
4910
+ const stage = lookupStageOwner(document.stage);
4911
+ if (!ordinaryDecisionBinding(binding) || owningDocuments.has(handle) || typeof access !== "string") return;
4912
+ const policy = staticFieldPolicy(stage.call, binding);
4913
+ if (!policy?.reusable || !policy.requestPaths) return;
4914
+ const prepared = prepareStaticOutputPaths(stage.call, binding, policy.requestPaths, access, true);
4915
+ if (!prepared) return;
4916
+ const decisions = settleStaticFieldBatch(
4917
+ handle,
4918
+ binding,
4919
+ prepared.map((policy2) => ({ field: policy2.path, policy: policy2 }))
4920
+ );
4921
+ return decisions && [...decisions].filter(([, allowed]) => allowed).map(([field]) => field);
4922
+ }
4923
+ function unchangedOutput(output, record3) {
4924
+ if (!matchesAuthorizationSnapshot(output, record3.snapshot)) return false;
4925
+ const identities = outputIdentities(output);
4926
+ return identities.length === record3.identities.length && identities.every((identity, i) => identity === record3.identities[i]);
4927
+ }
4928
+ function assertDocumentAuthorization(handle, use) {
4929
+ const { document: record3, stage } = validateDocumentOwner(handle);
4930
+ assertAuthorizationBinding(stage.call, use.binding);
4931
+ 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) {
4932
+ authorizationError("document call/access/stage mismatch");
4933
+ }
4934
+ const association = outputs.get(use.output);
4935
+ if (!association || association.handle !== handle || !unchangedOutput(use.output, association)) {
4936
+ authorizationError("unknown, replaced or mutated authorized output");
4937
+ }
4938
+ }
4939
+ function associateDocumentAuthorization(handle, binding, output) {
4940
+ const { stage } = validateDocumentOwner(handle);
4941
+ assertAuthorizationBinding(stage.call, binding);
4942
+ if (!output || typeof output !== "object") authorizationError("output must be an object");
4943
+ if (outputs.has(output)) {
4944
+ const previous = outputs.get(output);
4945
+ if (previous.handle !== handle || !unchangedOutput(output, previous))
4946
+ authorizationError("output already associated");
4947
+ return;
4948
+ }
4949
+ outputs.set(output, {
4950
+ handle,
4951
+ snapshot: copyAuthorizationValue(output, "document"),
4952
+ identities: outputIdentities(output)
4953
+ });
4954
+ }
4955
+ function transferDocumentAuthorization(handle, use, copy) {
4956
+ assertDocumentAuthorization(handle, use);
4957
+ associateDocumentAuthorization(handle, use.binding, copy);
4958
+ }
4959
+ function isKnownAuthorizationOutput(output) {
4960
+ return outputs.has(output);
4961
+ }
4962
+ function getAssociatedDocumentAuthorization(output, call) {
4963
+ const record3 = outputs.get(output);
4964
+ if (!record3 || !unchangedOutput(output, record3)) return void 0;
4965
+ const { stage } = validateDocumentOwner(record3.handle);
4966
+ if (call && getAuthorizationProvenance(stage.call) !== getAuthorizationProvenance(call)) return void 0;
4967
+ return record3.handle;
4968
+ }
4969
+ function transferDocumentAuthorizationGraph(source, copy, copyOrigins) {
4970
+ const seen = /* @__PURE__ */ new WeakSet();
4971
+ const visit = (source2, copy2) => {
4972
+ if (!copy2 || typeof copy2 !== "object" || seen.has(copy2)) return;
4973
+ seen.add(copy2);
4974
+ source2 = copyOrigins?.get(copy2) ?? source2;
4975
+ if (source2 instanceof Document3) source2 = source2._doc;
4976
+ const original = source2 && typeof source2 === "object" ? source2 : void 0;
4977
+ if (!original && !copyOrigins) return;
4978
+ const association = original && outputs.get(original);
4979
+ if (association) {
4980
+ const { document, stage } = validateDocumentOwner(association.handle);
4981
+ const outputAccess = readServiceAuthorizationAccess(stage.call, stage.binding).outputAccess;
4982
+ validateStageOwner(stage);
4983
+ transferDocumentAuthorization(
4984
+ association.handle,
4985
+ {
4986
+ binding: stage.binding,
4987
+ output: original,
4988
+ outputAccess,
4989
+ authorization: stage.call,
4990
+ stage: document.stage
4991
+ },
4992
+ copy2
4993
+ );
4994
+ }
4995
+ for (const key of Object.keys(copy2)) {
4996
+ const descriptor = original && Object.getOwnPropertyDescriptor(original, key);
4997
+ if (descriptor && "value" in descriptor) {
4998
+ visit(descriptor.value, copy2[key]);
4999
+ } else if (copyOrigins) {
5000
+ visit(void 0, copy2[key]);
5001
+ }
5002
+ }
5003
+ };
5004
+ visit(source, copy);
5005
+ }
5006
+ function createServiceOutputContext(diagnostic, handle, use) {
5007
+ assertDocumentAuthorization(handle, use);
5008
+ const rootOutput = use.output;
5009
+ const root = outputs.get(rootOutput);
5010
+ const graph = new Set(root.identities);
5011
+ const { stage } = validateDocumentOwner(handle);
5012
+ const call = stage.call;
5013
+ const context = { ...diagnostic };
5014
+ Object.defineProperties(context, {
5015
+ documentAuthorization: { value: handle, enumerable: false, writable: false, configurable: false },
5016
+ getDocumentAuthorization: {
5017
+ enumerable: false,
5018
+ writable: false,
5019
+ configurable: false,
5020
+ value(output) {
5021
+ if (!graph.has(output) || !unchangedOutput(rootOutput, root)) return void 0;
5022
+ const association = outputs.get(output);
5023
+ if (!association || !unchangedOutput(output, association)) return void 0;
5024
+ try {
5025
+ validateStageOwner(lookupStageOwner(lookupDocumentOwner(handle).stage));
5026
+ const { stage: child } = validateDocumentOwner(association.handle);
5027
+ if (getAuthorizationProvenance(child.call) !== getAuthorizationProvenance(call)) return void 0;
5028
+ return association.handle;
5029
+ } catch {
5030
+ return void 0;
5031
+ }
5032
+ }
5033
+ }
5034
+ });
5035
+ return context;
5036
+ }
5037
+ var stages, documents, outputs, unresolvedDocuments, owningDocuments;
5038
+ var init_document_authorization = __esm({
5039
+ "src/acl/document-authorization.ts"() {
5040
+ init_service_authorization();
5041
+ init_authorization_snapshot();
5042
+ init_output_projection();
5043
+ init_output_field_policy();
5044
+ stages = /* @__PURE__ */ new WeakMap();
5045
+ documents = /* @__PURE__ */ new WeakMap();
5046
+ outputs = /* @__PURE__ */ new WeakMap();
5047
+ unresolvedDocuments = /* @__PURE__ */ new WeakSet();
5048
+ owningDocuments = /* @__PURE__ */ new WeakMap();
5049
+ }
5050
+ });
5051
+
5052
+ // src/output/include-output.ts
5053
+ import { set as set5 } from "@web-ts-toolkit/utils";
5054
+ function prepareIncludeOutput(doc) {
5055
+ if (stateFor(doc)) return doc;
5056
+ const source = isolateDocForOutput(doc);
5057
+ transferDocumentAuthorizationGraph(doc, source);
5058
+ const working = deepIsolateValue(source);
5059
+ outputs2.set(working, { original: doc, source, attachments: [] });
5060
+ return working;
5061
+ }
5062
+ function attachIncludeOutput(doc, path, value) {
5063
+ const state = stateFor(doc);
5064
+ if (!state) throw new Error("Include attachment requires a prepared output row");
5065
+ state.attachments.push({ path, value });
5066
+ set5(doc, path, deepIsolateValue(value));
5067
+ }
5068
+ function getIncludeSource(doc) {
5069
+ return stateFor(doc)?.source ?? doc;
5070
+ }
5071
+ function getIncludeOriginal(doc) {
5072
+ return stateFor(doc)?.original ?? doc;
5073
+ }
5074
+ function restoreIncludeOutput(doc, output) {
5075
+ const attachments = stateFor(doc)?.attachments;
5076
+ if (!attachments?.length) return void 0;
5077
+ const origins = /* @__PURE__ */ new WeakMap();
5078
+ for (const { path, value } of attachments) {
5079
+ const copy = deepIsolateValue(value);
5080
+ if (copy !== null && typeof copy === "object") origins.set(copy, value);
5081
+ set5(output, path, copy);
5082
+ }
5083
+ return origins;
5084
+ }
5085
+ var outputs2, stateFor;
5086
+ var init_include_output = __esm({
5087
+ "src/output/include-output.ts"() {
5088
+ init_document_authorization();
5089
+ init_document();
5090
+ outputs2 = /* @__PURE__ */ new WeakMap();
5091
+ stateFor = (doc) => doc !== null && typeof doc === "object" ? outputs2.get(doc) : void 0;
4667
5092
  }
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
- );
5093
+ });
5094
+
5095
+ // src/helpers/request-work.ts
5096
+ function getRequestWorkState(req, runtime) {
5097
+ let owners = states.get(req);
5098
+ if (!owners) {
5099
+ owners = /* @__PURE__ */ new WeakMap();
5100
+ states.set(req, owners);
4684
5101
  }
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
- };
5102
+ let state = owners.get(runtime);
5103
+ if (!state) {
5104
+ const limits = resolveRequestComplexity(runtime.getGlobalOption("requestComplexity"));
5105
+ state = {
5106
+ totalQueries: 0,
5107
+ scheduler: new RequestConcurrencyScheduler(limits.maxBulkConcurrency),
5108
+ hookGate: new SharedHookGate(limits.maxHookConcurrency)
5109
+ };
5110
+ owners.set(runtime, state);
5111
+ }
5112
+ return state;
4763
5113
  }
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();
5114
+ var states;
5115
+ var init_request_work = __esm({
5116
+ "src/helpers/request-work.ts"() {
5117
+ init_request_complexity();
5118
+ init_concurrency();
5119
+ states = /* @__PURE__ */ new WeakMap();
4773
5120
  }
4774
5121
  });
4775
5122
 
@@ -4860,15 +5207,15 @@ import {
4860
5207
  isBoolean as isBoolean2,
4861
5208
  isEmpty as isEmpty2,
4862
5209
  isFunction as isFunction3,
4863
- isPlainObject as isPlainObject17,
5210
+ isPlainObject as isPlainObject18,
4864
5211
  isString as isString5
4865
5212
  } from "@web-ts-toolkit/utils";
4866
5213
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
4867
5214
  function isAndFilter(filter2) {
4868
- return !!filter2 && isPlainObject17(filter2) && Object.keys(filter2).length === 1 && isArray8(filter2.$and);
5215
+ return !!filter2 && isPlainObject18(filter2) && Object.keys(filter2).length === 1 && isArray8(filter2.$and);
4869
5216
  }
4870
5217
  function isMergeableClause(filter2) {
4871
- return !!filter2 && isPlainObject17(filter2) && Object.keys(filter2).every((key) => !key.startsWith("$"));
5218
+ return !!filter2 && isPlainObject18(filter2) && Object.keys(filter2).every((key) => !key.startsWith("$"));
4872
5219
  }
4873
5220
  function optimizeAndFilter(clausesInput) {
4874
5221
  const clauses = [];
@@ -4889,7 +5236,7 @@ function optimizeAndFilter(clausesInput) {
4889
5236
  const entries = Array.from(value, dedupeKey);
4890
5237
  return entries.every((entry) => entry !== void 0) ? `array:${JSON.stringify(entries)}` : void 0;
4891
5238
  }
4892
- if (isPlainObject17(value)) {
5239
+ if (isPlainObject18(value)) {
4893
5240
  const entries = Object.keys(value).sort().map((key) => [key, dedupeKey(value[key])]);
4894
5241
  return entries.every(([, entry]) => entry !== void 0) ? `object:${JSON.stringify(entries)}` : void 0;
4895
5242
  }
@@ -4937,7 +5284,7 @@ function optimizeAndFilter(clausesInput) {
4937
5284
  }
4938
5285
  function normalizeFilter(filter2) {
4939
5286
  if (filter2 === false) return false;
4940
- if (!filter2 || !isPlainObject17(filter2) || isEmpty2(filter2)) return null;
5287
+ if (!filter2 || !isPlainObject18(filter2) || isEmpty2(filter2)) return null;
4941
5288
  if (!isAndFilter(filter2)) {
4942
5289
  return filter2;
4943
5290
  }
@@ -5015,7 +5362,7 @@ async function setRequestPermissions(req) {
5015
5362
  if (hasFieldValue && owner === void 0) return;
5016
5363
  const globalPermissions = getGlobalOption("globalPermissions");
5017
5364
  const permissions = isFunction3(globalPermissions) ? await globalPermissions.call(req, req) : void 0;
5018
- if (isPlainObject17(permissions)) req[requestPermissionField] = permissions;
5365
+ if (isPlainObject18(permissions)) req[requestPermissionField] = permissions;
5019
5366
  else if (isArray8(permissions)) req[requestPermissionField] = arrayToRecord(permissions);
5020
5367
  else if (isString5(permissions)) req[requestPermissionField] = { [permissions]: true };
5021
5368
  else req[requestPermissionField] = {};
@@ -5414,7 +5761,7 @@ var init_filter_resolution = __esm({
5414
5761
  // src/acl/virtual-populate-execution.ts
5415
5762
  import { Document as Document4, mongo as mongo4 } from "mongoose";
5416
5763
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "util";
5417
- import { isPlainObject as isPlainObject20 } from "@web-ts-toolkit/utils";
5764
+ import { isPlainObject as isPlainObject21 } from "@web-ts-toolkit/utils";
5418
5765
  function projectVirtualPopulateView(source, selection, structurePaths = []) {
5419
5766
  const root = { children: /* @__PURE__ */ new Map() };
5420
5767
  for (const path of compactPersistedProjection(selection)) {
@@ -5446,8 +5793,8 @@ function equivalentVirtualPopulatePredicate(left, right) {
5446
5793
  }
5447
5794
  if (Array.isArray(left) || Array.isArray(right))
5448
5795
  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;
5796
+ if (isPlainObject21(left) || isPlainObject21(right)) {
5797
+ if (!isPlainObject21(left) || !isPlainObject21(right)) return false;
5451
5798
  const a = Object.keys(left), b = Object.keys(right);
5452
5799
  return a.length === b.length && a.every(
5453
5800
  (key, index) => key === b[index] && equivalentVirtualPopulatePredicate(
@@ -5850,7 +6197,7 @@ var init_virtual_populate_execution = __esm({
5850
6197
  publicViewIdentities = /* @__PURE__ */ new WeakMap();
5851
6198
  familyRawFetches = /* @__PURE__ */ new WeakMap();
5852
6199
  addressKey = (address) => JSON.stringify(address);
5853
- storage = (value) => value instanceof Document4 ? value._doc : isPlainObject20(value) ? value : void 0;
6200
+ storage = (value) => value instanceof Document4 ? value._doc : isPlainObject21(value) ? value : void 0;
5854
6201
  originalRef = (source, key) => {
5855
6202
  const record3 = storage(source);
5856
6203
  return {
@@ -5877,76 +6224,10 @@ var init_virtual_populate_execution = __esm({
5877
6224
  });
5878
6225
 
5879
6226
  // 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
- }
6227
+ import { types as types5 } from "util";
6228
+ import { isPlainObject as isPlainObject22 } from "@web-ts-toolkit/utils";
5948
6229
  function assertOwningOutputDocuments(handle) {
5949
- const owner = owningDocuments.get(handle);
6230
+ const owner = readOutputDocumentOwner(handle);
5950
6231
  if (owner) {
5951
6232
  readDocumentAuthorizationAccess(owner.handle, owner.binding);
5952
6233
  assertOwningOutputDocuments(owner.handle);
@@ -5956,7 +6237,7 @@ function prepareOutputDocumentAuthorization(authorization, binding, configuratio
5956
6237
  const access = readServiceAuthorizationAccess(authorization, binding);
5957
6238
  const key = `docPermissions.${access.docPermissionsAccess}`;
5958
6239
  const docPermissions = configuration.docPermissions;
5959
- const invariant = /^[A-Za-z0-9_-]+$/.test(access.docPermissionsAccess) && (docPermissions == null || isPlainObject21(docPermissions));
6240
+ const invariant = /^[A-Za-z0-9_-]+$/.test(access.docPermissionsAccess) && (docPermissions == null || isPlainObject22(docPermissions));
5960
6241
  const option = invariant ? getCapturedAuthorizationOption(configuration, key) : void 0;
5961
6242
  const hook = typeof option === "function" ? option : void 0;
5962
6243
  const resolveHook = invariant ? () => hook : () => {
@@ -5986,7 +6267,7 @@ async function resolveOutputDocumentAuthorizationWithHook(args, access, resolveH
5986
6267
  try {
5987
6268
  const run = () => hook.call(this, doc, permissions, args.context);
5988
6269
  const grants = await getRequestWorkState(binding.request, binding.runtime).hookGate.run(run);
5989
- return isPlainObject21(grants) ? grants : {};
6270
+ return isPlainObject22(grants) ? grants : {};
5990
6271
  } catch (error2) {
5991
6272
  warn("docPermissions hook failed; applying empty document permissions", {
5992
6273
  modelName: binding.modelName,
@@ -5997,14 +6278,12 @@ async function resolveOutputDocumentAuthorizationWithHook(args, access, resolveH
5997
6278
  return {};
5998
6279
  }
5999
6280
  });
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 });
6281
+ bindOutputDocumentOwner(handle, args.knownOutput, args.owningDocument, args.owningBinding);
6003
6282
  return handle;
6004
6283
  }
6005
6284
  function evaluateRequestRule(handle, binding, entry, prefix, access) {
6006
6285
  assertOwningOutputDocuments(handle);
6007
- const owner = owningDocuments.get(handle);
6286
+ const owner = readOutputDocumentOwner(handle);
6008
6287
  if (owner && !entry.path.startsWith(`${(binding.scopePath ?? []).join(".")}.`)) {
6009
6288
  return evaluateRequestRule(owner.handle, owner.binding, entry, prefix, access);
6010
6289
  }
@@ -6038,7 +6317,7 @@ function evaluateAuthorizedOutputField(handle, binding, field) {
6038
6317
  const policy = callFieldPolicy(authorization, binding);
6039
6318
  const { outputAccess } = readDocumentAuthorizationAccess(handle, binding);
6040
6319
  const prepared = prepareOutputPath(policy, authorization, binding, path, outputAccess);
6041
- const unresolved = unresolvedDocuments.has(handle);
6320
+ const unresolved = isUnresolvedOutputDocument(handle);
6042
6321
  const state = unresolved ? prepared.state ?? classifyEffectiveFieldAuthorization({
6043
6322
  path,
6044
6323
  rules: prepared.entries.map((entry) => entry.rule),
@@ -6061,12 +6340,18 @@ function evaluateAuthorizedOutputField(handle, binding, field) {
6061
6340
  assertOwningOutputDocuments(handle);
6062
6341
  return allowed;
6063
6342
  });
6064
- return owningDocuments.has(handle) ? decision.then((allowed) => {
6343
+ return readOutputDocumentOwner(handle) ? decision.then((allowed) => {
6065
6344
  assertOwningOutputDocuments(handle);
6066
6345
  return allowed;
6067
6346
  }) : decision;
6068
6347
  }
6069
6348
  async function requestOutputFieldPaths(handle, binding, access) {
6349
+ const staticFields = tryStaticRequestFieldPaths(handle, binding, access);
6350
+ if (staticFields) {
6351
+ await Promise.resolve();
6352
+ readDocumentAuthorizationAccess(handle, binding);
6353
+ return staticFields;
6354
+ }
6070
6355
  const { authorization } = readDocumentAuthorizationAccess(handle, binding);
6071
6356
  assertOwningOutputDocuments(handle);
6072
6357
  const policy = callFieldPolicy(authorization, binding);
@@ -6115,7 +6400,7 @@ function copyOutputValue(value, plan, path) {
6115
6400
  const visit = (input, current) => {
6116
6401
  if (Array.isArray(input)) return input.map((entry) => visit(entry, current));
6117
6402
  if (input instanceof Map) return visit(Object.fromEntries(input), current);
6118
- if (!isPlainObject21(input)) return deepIsolateValue(input);
6403
+ if (!isPlainObject22(input)) return deepIsolateValue(input);
6119
6404
  const output = {};
6120
6405
  for (const [key, entry] of Object.entries(input)) {
6121
6406
  const child = `${current}.${key}`;
@@ -6131,7 +6416,7 @@ function copyOutputValue(value, plan, path) {
6131
6416
  }
6132
6417
  function copyAuthorizedReference(value, plan, path) {
6133
6418
  if (Array.isArray(value)) return value.map((entry) => copyAuthorizedReference(entry, plan, path));
6134
- if (!isPlainObject21(value)) return deepIsolateValue(value);
6419
+ if (!isPlainObject22(value)) return deepIsolateValue(value);
6135
6420
  const handle = getAssociatedDocumentAuthorization(value, plan.authorization);
6136
6421
  if (handle) {
6137
6422
  const copy = deepIsolateValue(value);
@@ -6144,8 +6429,8 @@ function retainOutputMetadata(output, source, configuration, scope2) {
6144
6429
  if (scope2.length || configuration.stripPermissionsField) return;
6145
6430
  const parts = (configuration.documentPermissionField ?? "_permissions").split(".");
6146
6431
  let value = source;
6147
- for (const part of parts) value = isPlainObject21(value) ? value[part] : void 0;
6148
- if (!isPlainObject21(value)) return;
6432
+ for (const part of parts) value = isPlainObject22(value) ? value[part] : void 0;
6433
+ if (!isPlainObject22(value)) return;
6149
6434
  const keys2 = configuration.exposedDocPermissionKeys;
6150
6435
  const metadata = Object.fromEntries(
6151
6436
  Object.entries(value).filter(
@@ -6155,7 +6440,7 @@ function retainOutputMetadata(output, source, configuration, scope2) {
6155
6440
  const copy = { ...output };
6156
6441
  let target = copy;
6157
6442
  for (const part of parts.slice(0, -1)) {
6158
- target[part] = isPlainObject21(target[part]) ? { ...target[part] } : {};
6443
+ target[part] = isPlainObject22(target[part]) ? { ...target[part] } : {};
6159
6444
  target = target[part];
6160
6445
  }
6161
6446
  target[parts[parts.length - 1]] = deepIsolateValue(metadata);
@@ -6164,27 +6449,37 @@ function retainOutputMetadata(output, source, configuration, scope2) {
6164
6449
  attachPermissionsAlias(output, parts.join("."));
6165
6450
  }
6166
6451
  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 };
6452
+ return planAuthorizedModelProjection({ authorization, binding, effectiveSelect: [] });
6453
+ }
6454
+ function primitiveHelperFields(source, plan) {
6455
+ if (types5.isProxy(source)) return;
6456
+ const canonical = readStaticOutputPlanFields(plan, plan.authorization);
6457
+ if (!canonical) return;
6458
+ const fields = [];
6459
+ for (const field of canonical) {
6460
+ const slot = Object.getOwnPropertyDescriptor(source, field);
6461
+ if (!slot) continue;
6462
+ if (!("value" in slot)) return;
6463
+ const value = slot.value;
6464
+ if (value !== null && typeof value === "object" || typeof value === "function" || typeof value === "symbol")
6465
+ return;
6466
+ if (value !== void 0) fields.push(field);
6467
+ }
6468
+ return fields;
6182
6469
  }
6183
6470
  async function filterExistingOutput(source, plan, handle, associated) {
6184
6471
  const binding = plan.authorizationBinding;
6185
6472
  const { configuration } = readServiceAuthorization(plan.authorization, binding);
6186
6473
  const output = {};
6187
6474
  const fields = [];
6475
+ const primitiveFields = primitiveHelperFields(source, plan);
6476
+ const staticDecisions = primitiveFields && tryStaticOutputFieldDecisions(handle, binding, plan, primitiveFields);
6477
+ if (staticDecisions) {
6478
+ await Promise.resolve();
6479
+ if (associated) assertDocumentAuthorization(handle, { binding, output: source, outputAccess: plan.outputAccess });
6480
+ else readDocumentAuthorizationAccess(handle, binding);
6481
+ if (!readStaticOutputPlanFields(plan, plan.authorization)) authorizationError("changed static output plan");
6482
+ }
6188
6483
  for (const field of /* @__PURE__ */ new Set([...plan.outputPersistedFields, ...plan.outputVirtualNames])) {
6189
6484
  if (!Object.prototype.hasOwnProperty.call(source, field) || source[field] === void 0) continue;
6190
6485
  const childPlan = plan.childPlans[field];
@@ -6197,7 +6492,7 @@ async function filterExistingOutput(source, plan, handle, associated) {
6197
6492
  for (const entry of value2) values.push(await one(entry) ?? null);
6198
6493
  return values;
6199
6494
  }
6200
- if (!isPlainObject21(value2)) return value2 === null ? null : void 0;
6495
+ if (!isPlainObject22(value2)) return value2 === null ? null : void 0;
6201
6496
  const childHandle = associated ? getAssociatedDocumentAuthorization(value2) : void 0;
6202
6497
  let child = scoped;
6203
6498
  if (childHandle) {
@@ -6225,7 +6520,7 @@ async function filterExistingOutput(source, plan, handle, associated) {
6225
6520
  const value = await one(source[field]);
6226
6521
  if (value !== void 0) output[field] = value;
6227
6522
  fields.push(...childFields);
6228
- } else if (await evaluateAuthorizedOutputField(handle, binding, field)) {
6523
+ } else if (staticDecisions ? staticDecisions.get(field) === true : await evaluateAuthorizedOutputField(handle, binding, field)) {
6229
6524
  const path = [...binding.scopePath ?? [], field].join(".");
6230
6525
  output[field] = configuration.catalog.referencePaths?.some((p) => matchesCatalogPattern(p, path)) ? copyAuthorizedReference(source[field], plan, path) : copyOutputValue(source[field], plan, path);
6231
6526
  if (associated) transferDocumentAuthorizationGraph(source[field], output[field]);
@@ -6277,7 +6572,7 @@ async function filterModelOutputForHelper(args) {
6277
6572
  const plan = helperPlan(normalized.authorization, binding);
6278
6573
  if (args.doc == null) return { output: args.doc, fields: [] };
6279
6574
  const source = isolateDocForOutput(args.doc);
6280
- if (!isPlainObject21(source)) return authorizationError("output helper requires one plain or hydrated document");
6575
+ if (!isPlainObject22(source)) return authorizationError("output helper requires one plain or hydrated document");
6281
6576
  const knownOutput = !!args.doc && typeof args.doc === "object" && isKnownAuthorizationOutput(args.doc);
6282
6577
  const handle = await resolveOutputDocumentAuthorization({
6283
6578
  authorization: normalized.authorization,
@@ -6288,7 +6583,6 @@ async function filterModelOutputForHelper(args) {
6288
6583
  });
6289
6584
  return filterExistingOutput(source, plan, handle, false);
6290
6585
  }
6291
- var unresolvedDocuments, owningDocuments, fieldPolicies;
6292
6586
  var init_output_field_filter = __esm({
6293
6587
  "src/acl/output-field-filter.ts"() {
6294
6588
  init_permissions_alias();
@@ -6302,9 +6596,7 @@ var init_output_field_filter = __esm({
6302
6596
  init_field_authorization();
6303
6597
  init_field_catalog();
6304
6598
  init_output_projection();
6305
- unresolvedDocuments = /* @__PURE__ */ new WeakSet();
6306
- owningDocuments = /* @__PURE__ */ new WeakMap();
6307
- fieldPolicies = /* @__PURE__ */ new WeakMap();
6599
+ init_output_field_policy();
6308
6600
  }
6309
6601
  });
6310
6602
 
@@ -6373,7 +6665,7 @@ __export(finalize_model_output_exports, {
6373
6665
  finalizeModelOutput: () => finalizeModelOutput,
6374
6666
  finalizeModelOutputs: () => finalizeModelOutputs
6375
6667
  });
6376
- import { get as get9, isPlainObject as isPlainObject22, set as set7 } from "@web-ts-toolkit/utils";
6668
+ import { get as get9, isPlainObject as isPlainObject23, set as set7 } from "@web-ts-toolkit/utils";
6377
6669
  function assertFinalizerCall(args, prepared) {
6378
6670
  const plan = args.plan;
6379
6671
  const binding = plan.authorizationBinding;
@@ -6415,8 +6707,8 @@ async function finalizeSingleDoc(args, input, prepared) {
6415
6707
  const privateRow = args.virtualPopulateRow ?? (original && typeof original === "object" ? getVirtualPopulateRow(original) : void 0);
6416
6708
  const privateAddress = args.virtualPopulateAddress ?? [];
6417
6709
  const isolated = isolateDocForOutput(input);
6418
- const output = isPlainObject22(isolated) ? isolated : {};
6419
- if (captured && isPlainObject22(input))
6710
+ const output = isPlainObject23(isolated) ? isolated : {};
6711
+ if (captured && isPlainObject23(input))
6420
6712
  for (const key of Object.keys(output)) {
6421
6713
  transferDocumentAuthorizationGraph(input[key], output[key]);
6422
6714
  }
@@ -6468,7 +6760,7 @@ async function finalizeSingleDoc(args, input, prepared) {
6468
6760
  );
6469
6761
  continue;
6470
6762
  }
6471
- if (captured && !isPlainObject22(rawContainer) && !Array.isArray(rawContainer)) {
6763
+ if (captured && !isPlainObject23(rawContainer) && !Array.isArray(rawContainer)) {
6472
6764
  delete output[containerName];
6473
6765
  continue;
6474
6766
  }
@@ -6494,7 +6786,7 @@ async function finalizeSingleDoc(args, input, prepared) {
6494
6786
  const finalizeOneChild = async (rawChild, address) => {
6495
6787
  if (captured && Array.isArray(rawChild))
6496
6788
  return mapWithConcurrencyLimit(rawChild, limit, (entry, index) => finalizeOneChild(entry, [...address, index]));
6497
- if (!isPlainObject22(rawChild) && !Array.isArray(rawChild)) return captured ? null : deepIsolateValue(rawChild);
6789
+ if (!isPlainObject23(rawChild) && !Array.isArray(rawChild)) return captured ? null : deepIsolateValue(rawChild);
6498
6790
  if (args.traversal?.finalizeEmbeddedChildren) {
6499
6791
  return args.traversal.finalizeEmbeddedChildren({
6500
6792
  containerName,
@@ -6527,7 +6819,7 @@ async function finalizeSingleDoc(args, input, prepared) {
6527
6819
  (entry, index) => finalizeOneChild(entry, [...privateAddress, containerName, index])
6528
6820
  );
6529
6821
  output[containerName] = finalized;
6530
- } else if (isPlainObject22(rawContainer)) {
6822
+ } else if (isPlainObject23(rawContainer)) {
6531
6823
  output[containerName] = await finalizeOneChild(rawContainer, [
6532
6824
  ...privateAddress,
6533
6825
  containerName
@@ -6572,7 +6864,7 @@ async function finalizeSingleDoc(args, input, prepared) {
6572
6864
  };
6573
6865
  let relatedPreparation;
6574
6866
  const finalizeOneRelated = async (rawChild, originalChild = rawChild) => {
6575
- if (!isPlainObject22(rawChild) && !Array.isArray(rawChild)) return rawChild;
6867
+ if (!isPlainObject23(rawChild) && !Array.isArray(rawChild)) return rawChild;
6576
6868
  if (typeof rawChild?._bsontype === "string") return rawChild;
6577
6869
  const childOriginal = getIncludeOriginal(originalChild);
6578
6870
  const childRow = childOriginal && typeof childOriginal === "object" ? getVirtualPopulateRow(childOriginal) : void 0;
@@ -6597,7 +6889,7 @@ async function finalizeSingleDoc(args, input, prepared) {
6597
6889
  limit,
6598
6890
  (entry, index) => finalizeOneRelated(entry, Array.isArray(originalRelated) ? originalRelated[index] : void 0)
6599
6891
  );
6600
- } else if (isPlainObject22(rawRelated)) {
6892
+ } else if (isPlainObject23(rawRelated)) {
6601
6893
  finalized = await finalizeOneRelated(rawRelated, originalRelated);
6602
6894
  } else {
6603
6895
  continue;
@@ -6682,10 +6974,17 @@ async function finalizeSingleDoc(args, input, prepared) {
6682
6974
  }
6683
6975
  const eligiblePersisted = new Set(plan.outputPersistedFields ?? []);
6684
6976
  const eligibleVirtuals = new Set(plan.outputVirtualNames ?? []);
6977
+ const staticDecisions = documentAuthorization ? tryStaticOutputFieldDecisions(documentAuthorization, binding, plan, [...eligiblePersisted]) : void 0;
6978
+ if (staticDecisions) {
6979
+ await Promise.resolve();
6980
+ assertFinalizerCall(args, prepared);
6981
+ readDocumentAuthorizationAccess(documentAuthorization, binding);
6982
+ if (!readStaticOutputPlanFields(plan, prepared.authorization)) authorizationError("changed static output plan");
6983
+ }
6685
6984
  const allowedPersisted = [];
6686
6985
  for (const field of eligiblePersisted) {
6687
6986
  if (documentAuthorization) {
6688
- if (plan.childPlans[field] || await evaluateAuthorizedOutputField(documentAuthorization, binding, field))
6987
+ if (plan.childPlans[field] || (staticDecisions ? staticDecisions.get(field) === true : await evaluateAuthorizedOutputField(documentAuthorization, binding, field)))
6689
6988
  allowedPersisted.push(field);
6690
6989
  continue;
6691
6990
  }
@@ -6763,6 +7062,10 @@ async function finalizeSingleDoc(args, input, prepared) {
6763
7062
  stage: readDocumentAuthorizationAccess(documentAuthorization, binding).stage
6764
7063
  })
6765
7064
  );
7065
+ if (staticDecisions) {
7066
+ assertFinalizerCall(args, prepared);
7067
+ readDocumentAuthorizationAccess(documentAuthorization, binding);
7068
+ }
6766
7069
  }
6767
7070
  void getRetainedAssociations;
6768
7071
  return trimmed;
@@ -6823,22 +7126,23 @@ var init_finalize_model_output = __esm({
6823
7126
  init_output_field_filter();
6824
7127
  init_field_authorization();
6825
7128
  init_field_catalog();
7129
+ init_output_projection();
6826
7130
  init_virtual_populate_execution();
6827
7131
  init_include_output();
6828
- isVirtualContainerValue3 = (value) => isPlainObject22(value) && "sub" in value;
7132
+ isVirtualContainerValue3 = (value) => isPlainObject23(value) && "sub" in value;
6829
7133
  getScopeVirtualsObject2 = (rootVirtuals, scopePath) => {
6830
- if (!rootVirtuals || !isPlainObject22(rootVirtuals)) return null;
7134
+ if (!rootVirtuals || !isPlainObject23(rootVirtuals)) return null;
6831
7135
  if (scopePath.length === 0) return rootVirtuals;
6832
7136
  let current = rootVirtuals;
6833
7137
  for (let i = 0; i < scopePath.length; i += 2) {
6834
7138
  const field = scopePath[i];
6835
7139
  const subMarker = scopePath[i + 1];
6836
7140
  if (!field || subMarker !== "sub") return null;
6837
- if (!isPlainObject22(current)) return null;
7141
+ if (!isPlainObject23(current)) return null;
6838
7142
  const container = current[field];
6839
7143
  if (!isVirtualContainerValue3(container)) return null;
6840
7144
  current = container.sub;
6841
- if (!isPlainObject22(current)) return null;
7145
+ if (!isPlainObject23(current)) return null;
6842
7146
  }
6843
7147
  return current;
6844
7148
  };
@@ -6851,11 +7155,11 @@ var init_finalize_model_output = __esm({
6851
7155
  return Object.entries(scopeVirtuals).filter(([, v]) => v !== void 0 && !isVirtualContainerValue3(v)).map(([k]) => k);
6852
7156
  };
6853
7157
  getScopedPermissionSchema2 = (root, scopePath) => {
6854
- if (!root || !isPlainObject22(root)) return null;
7158
+ if (!root || !isPlainObject23(root)) return null;
6855
7159
  if (scopePath.length === 0) return root;
6856
7160
  try {
6857
7161
  const scoped = get9(root, scopePath.join("."));
6858
- return isPlainObject22(scoped) ? scoped : null;
7162
+ return isPlainObject23(scoped) ? scoped : null;
6859
7163
  } catch {
6860
7164
  return null;
6861
7165
  }
@@ -6914,7 +7218,7 @@ var init_finalize_model_output = __esm({
6914
7218
  const grants = await args.sharedGate.run(
6915
7219
  () => hook.call(args.request, isolatedForHook, globalPerms, scopeContext)
6916
7220
  );
6917
- const normalized = isPlainObject22(grants) ? grants : {};
7221
+ const normalized = isPlainObject23(grants) ? grants : {};
6918
7222
  scopeContext.docPermissions = normalized;
6919
7223
  return normalized;
6920
7224
  }
@@ -6936,11 +7240,11 @@ var init_finalize_model_output = __esm({
6936
7240
  });
6937
7241
 
6938
7242
  // src/index.ts
6939
- import { isPlainObject as isPlainObject31, isString as isString10, isUndefined as isUndefined4 } from "@web-ts-toolkit/utils";
7243
+ import { isPlainObject as isPlainObject32, isString as isString10, isUndefined as isUndefined4 } from "@web-ts-toolkit/utils";
6940
7244
 
6941
7245
  // src/middleware.ts
6942
7246
  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";
7247
+ import { isArray as isArray13, isFunction as isFunction7, isPlainObject as isPlainObject28, isString as isString7 } from "@web-ts-toolkit/utils";
6944
7248
 
6945
7249
  // src/core.ts
6946
7250
  init_public_admission();
@@ -6975,7 +7279,7 @@ import {
6975
7279
  forEach as forEach3,
6976
7280
  get as get8,
6977
7281
  isArray as isArray9,
6978
- isPlainObject as isPlainObject18,
7282
+ isPlainObject as isPlainObject19,
6979
7283
  set as set6,
6980
7284
  uniq
6981
7285
  } from "@web-ts-toolkit/utils";
@@ -7100,7 +7404,7 @@ init_public_admission();
7100
7404
  // src/correlated-includes.ts
7101
7405
  init_request_complexity();
7102
7406
  init_sort_policy();
7103
- import { cloneDeep, isArray as isArray6, isPlainObject as isPlainObject15 } from "@web-ts-toolkit/utils";
7407
+ import { cloneDeep, isArray as isArray7, isPlainObject as isPlainObject17 } from "@web-ts-toolkit/utils";
7104
7408
  var PARENT_MARKER_KEY = "$parent";
7105
7409
  var ESCAPE_WRAPPER_KEY = "$escape";
7106
7410
  var SUBQUERY_PAYLOAD_KEYS = /* @__PURE__ */ new Set(["$$sq", "$$date"]);
@@ -7111,10 +7415,10 @@ var FIELD_SEGMENT_PATTERN = /^[A-Za-z_][A-Za-z0-9_$]*$/;
7111
7415
  var ARRAY_INDEX_SEGMENT_PATTERN = /^(0|[1-9]\d*)$/;
7112
7416
  var ownKeys = (value) => Object.keys(value);
7113
7417
  function isParentRefMarker(value) {
7114
- return isPlainObject15(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === PARENT_MARKER_KEY;
7418
+ return isPlainObject17(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === PARENT_MARKER_KEY;
7115
7419
  }
7116
7420
  function isEscapedParentRef(value) {
7117
- return isPlainObject15(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === ESCAPE_WRAPPER_KEY;
7421
+ return isPlainObject17(value) && ownKeys(value).length === 1 && ownKeys(value)[0] === ESCAPE_WRAPPER_KEY;
7118
7422
  }
7119
7423
  function hasMarkerKey(value) {
7120
7424
  return ownKeys(value).includes(PARENT_MARKER_KEY) || ownKeys(value).includes(ESCAPE_WRAPPER_KEY);
@@ -7133,12 +7437,12 @@ function containsParentMarkerShape(value) {
7133
7437
  const seen = /* @__PURE__ */ new Set();
7134
7438
  const visit = (current) => {
7135
7439
  if (isParentRefMarker(current) || isEscapedParentRef(current)) return true;
7136
- if (isArray6(current)) {
7440
+ if (isArray7(current)) {
7137
7441
  if (seen.has(current)) return false;
7138
7442
  seen.add(current);
7139
7443
  return current.some(visit);
7140
7444
  }
7141
- if (isPlainObject15(current)) {
7445
+ if (isPlainObject17(current)) {
7142
7446
  if (seen.has(current)) return false;
7143
7447
  seen.add(current);
7144
7448
  if (hasMarkerKey(current)) return true;
@@ -7168,7 +7472,7 @@ function scanTemplateValueNode(value, path, issues) {
7168
7472
  }
7169
7473
  return;
7170
7474
  }
7171
- if (isPlainObject15(value)) {
7475
+ if (isPlainObject17(value)) {
7172
7476
  if (hasMarkerKey(value)) {
7173
7477
  issues.push({
7174
7478
  message: 'Malformed $parent reference: objects carrying $parent must be exactly { "$parent": "<field>" }',
@@ -7179,7 +7483,7 @@ function scanTemplateValueNode(value, path, issues) {
7179
7483
  scanTemplateObjectEntries(value, path, issues);
7180
7484
  return;
7181
7485
  }
7182
- if (isArray6(value)) {
7486
+ if (isArray7(value)) {
7183
7487
  value.forEach((item, index) => scanTemplateValueNode(item, [...path, index], issues));
7184
7488
  }
7185
7489
  }
@@ -7220,7 +7524,7 @@ function scanTemplateObjectEntries(obj, basePath, issues) {
7220
7524
  continue;
7221
7525
  }
7222
7526
  if (LOGICAL_CLAUSE_KEYS.has(key)) {
7223
- if (!isArray6(child)) {
7527
+ if (!isArray7(child)) {
7224
7528
  scanTemplateValueNode(child, childPath, issues);
7225
7529
  continue;
7226
7530
  }
@@ -7233,7 +7537,7 @@ function scanTemplateObjectEntries(obj, basePath, issues) {
7233
7537
  });
7234
7538
  return;
7235
7539
  }
7236
- if (isPlainObject15(clause)) {
7540
+ if (isPlainObject17(clause)) {
7237
7541
  scanTemplateObjectEntries(clause, clausePath, issues);
7238
7542
  }
7239
7543
  });
@@ -7244,7 +7548,7 @@ function scanTemplateObjectEntries(obj, basePath, issues) {
7244
7548
  }
7245
7549
  function validateCorrelatedFilterTemplate(filter2) {
7246
7550
  const issues = [];
7247
- if (!isPlainObject15(filter2)) {
7551
+ if (!isPlainObject17(filter2)) {
7248
7552
  issues.push({ message: "Correlated include filter must be an object", path: [] });
7249
7553
  return issues;
7250
7554
  }
@@ -7287,13 +7591,13 @@ function collectFilterReferencePaths(filter2) {
7287
7591
  return;
7288
7592
  }
7289
7593
  if (isEscapedParentRef(value)) return;
7290
- if (isArray6(value)) {
7594
+ if (isArray7(value)) {
7291
7595
  if (seen.has(value)) return;
7292
7596
  seen.add(value);
7293
7597
  value.forEach(visitValue);
7294
7598
  return;
7295
7599
  }
7296
- if (isPlainObject15(value)) {
7600
+ if (isPlainObject17(value)) {
7297
7601
  if (seen.has(value)) return;
7298
7602
  seen.add(value);
7299
7603
  for (const [key, child] of Object.entries(value)) {
@@ -7339,7 +7643,7 @@ function getOwnPathValue(parent, path) {
7339
7643
  return current;
7340
7644
  }
7341
7645
  function cloneSubstitutedValue(value) {
7342
- if (isPlainObject15(value) || isArray6(value)) return cloneDeep(value);
7646
+ if (isPlainObject17(value) || isArray7(value)) return cloneDeep(value);
7343
7647
  return value;
7344
7648
  }
7345
7649
  function literalParentRefObject(path) {
@@ -7380,7 +7684,7 @@ function resolveObjectEntries(obj, parent) {
7380
7684
  continue;
7381
7685
  }
7382
7686
  if (LOGICAL_CLAUSE_KEYS.has(key)) {
7383
- if (!isArray6(child)) {
7687
+ if (!isArray7(child)) {
7384
7688
  out[key] = resolveValueNode(child, parent, false);
7385
7689
  continue;
7386
7690
  }
@@ -7388,7 +7692,7 @@ function resolveObjectEntries(obj, parent) {
7388
7692
  if (isParentRefMarker(clause) || isEscapedParentRef(clause)) {
7389
7693
  throw new CorrelatedReferenceError(`Unsupported $parent reference as a direct ${key} clause`);
7390
7694
  }
7391
- if (!isPlainObject15(clause)) return cloneSubstitutedValue(clause);
7695
+ if (!isPlainObject17(clause)) return cloneSubstitutedValue(clause);
7392
7696
  return resolveObjectEntries(clause, parent);
7393
7697
  });
7394
7698
  continue;
@@ -7417,10 +7721,10 @@ function resolveValueNode(template, parent, bare) {
7417
7721
  }
7418
7722
  const value = getOwnPathValue(parent, path);
7419
7723
  if (value === void 0 || value === null) throw UNRESOLVABLE;
7420
- if (bare && isPlainObject15(value)) return { $eq: cloneDeep(value) };
7724
+ if (bare && isPlainObject17(value)) return { $eq: cloneDeep(value) };
7421
7725
  return cloneSubstitutedValue(value);
7422
7726
  }
7423
- if (isPlainObject15(template)) {
7727
+ if (isPlainObject17(template)) {
7424
7728
  if (hasMarkerKey(template)) {
7425
7729
  throw new CorrelatedReferenceError(
7426
7730
  'Malformed $parent reference: objects carrying $parent must be exactly { "$parent": "<field>" }'
@@ -7428,7 +7732,7 @@ function resolveValueNode(template, parent, bare) {
7428
7732
  }
7429
7733
  return resolveObjectEntries(template, parent);
7430
7734
  }
7431
- if (isArray6(template)) {
7735
+ if (isArray7(template)) {
7432
7736
  return template.map((item) => resolveValueNode(item, parent, false));
7433
7737
  }
7434
7738
  return template;
@@ -7462,7 +7766,7 @@ function resolveCorrelatedIdTemplate(id, parent) {
7462
7766
  }
7463
7767
  function resolveCorrelatedFilterTemplate(filter2, parent) {
7464
7768
  try {
7465
- if (!isPlainObject15(filter2) || isParentRefMarker(filter2) || isEscapedParentRef(filter2)) {
7769
+ if (!isPlainObject17(filter2) || isParentRefMarker(filter2) || isEscapedParentRef(filter2)) {
7466
7770
  throw new CorrelatedReferenceError("Correlated include filter must be an object");
7467
7771
  }
7468
7772
  return { status: "resolved", filter: resolveObjectEntries(filter2, parent) };
@@ -7477,7 +7781,7 @@ function validateExpandedCorrelatedOperands(expanded, limits) {
7477
7781
  var MAX_NESTED_INCLUDE_DEPTH = 10;
7478
7782
  function validateCorrelatedArgsShape(args, op, depth) {
7479
7783
  if (args === void 0) return [];
7480
- if (!isPlainObject15(args)) return ["Correlated include args must be an object"];
7784
+ if (!isPlainObject17(args)) return ["Correlated include args must be an object"];
7481
7785
  const record3 = args;
7482
7786
  const allowed = op === "list" ? /* @__PURE__ */ new Set(["select", "sort", "skip", "limit", "page", "pageSize", "include"]) : /* @__PURE__ */ new Set(["select", "sort", "include"]);
7483
7787
  for (const key of Object.keys(record3)) {
@@ -7499,7 +7803,7 @@ function validateCorrelatedArgsShape(args, op, depth) {
7499
7803
  return [];
7500
7804
  }
7501
7805
  function validateCorrelatedIncludeShape(entry, depth = 0) {
7502
- if (!isPlainObject15(entry)) return ["Correlated include must be an object"];
7806
+ if (!isPlainObject17(entry)) return ["Correlated include must be an object"];
7503
7807
  const record3 = entry;
7504
7808
  if (record3.mode !== "correlated") return ['Correlated include mode must be "correlated"'];
7505
7809
  if (typeof record3.model !== "string" || record3.model.length === 0)
@@ -7512,7 +7816,7 @@ function validateCorrelatedIncludeShape(entry, depth = 0) {
7512
7816
  if ("localField" in record3 || "foreignField" in record3) {
7513
7817
  return ["Correlated includes must not carry localField or foreignField"];
7514
7818
  }
7515
- if (record3.options !== void 0 && !(isPlainObject15(record3.options) && Object.keys(record3.options).length === 0)) {
7819
+ if (record3.options !== void 0 && !(isPlainObject17(record3.options) && Object.keys(record3.options).length === 0)) {
7516
7820
  return ["Correlated include options must be absent or empty"];
7517
7821
  }
7518
7822
  const hasId = record3.id !== void 0;
@@ -7534,7 +7838,7 @@ function validateCorrelatedIncludeShape(entry, depth = 0) {
7534
7838
  return validateCorrelatedArgsShape(record3.args, record3.op, depth);
7535
7839
  }
7536
7840
  function isCorrelatedInclude(value) {
7537
- return isPlainObject15(value) && value.mode === "correlated";
7841
+ return isPlainObject17(value) && value.mode === "correlated";
7538
7842
  }
7539
7843
 
7540
7844
  // src/services/base.ts
@@ -8271,20 +8575,20 @@ var copyAuthorizedOutput = (value) => {
8271
8575
  transferDocumentAuthorizationGraph(value, copy);
8272
8576
  return copy;
8273
8577
  };
8274
- var isVirtualContainerValueForGuard = (value) => isPlainObject18(value) && "sub" in value;
8578
+ var isVirtualContainerValueForGuard = (value) => isPlainObject19(value) && "sub" in value;
8275
8579
  var getScopeVirtualsForGuard = (rootVirtuals, scopePath) => {
8276
- if (!rootVirtuals || !isPlainObject18(rootVirtuals)) return null;
8580
+ if (!rootVirtuals || !isPlainObject19(rootVirtuals)) return null;
8277
8581
  if (scopePath.length === 0) return rootVirtuals;
8278
8582
  let current = rootVirtuals;
8279
8583
  for (let i = 0; i < scopePath.length; i += 2) {
8280
8584
  const field = scopePath[i];
8281
8585
  const subMarker = scopePath[i + 1];
8282
8586
  if (!field || subMarker !== "sub") return null;
8283
- if (!isPlainObject18(current)) return null;
8587
+ if (!isPlainObject19(current)) return null;
8284
8588
  const container = current[field];
8285
8589
  if (!isVirtualContainerValueForGuard(container)) return null;
8286
8590
  current = container.sub;
8287
- if (!isPlainObject18(current)) return null;
8591
+ if (!isPlainObject19(current)) return null;
8288
8592
  }
8289
8593
  return current;
8290
8594
  };
@@ -8350,7 +8654,7 @@ var sanitizeSubScopeVirtualKeys = (data, snapshot, sub) => {
8350
8654
  for (const entry of value) stripScope(entry, currentScope);
8351
8655
  return;
8352
8656
  }
8353
- if (!isPlainObject18(value)) return;
8657
+ if (!isPlainObject19(value)) return;
8354
8658
  const record3 = value;
8355
8659
  const leaves = getScopeVirtualLeafNames(snapshot, currentScope);
8356
8660
  for (const leaf of leaves) {
@@ -8363,7 +8667,7 @@ var sanitizeSubScopeVirtualKeys = (data, snapshot, sub) => {
8363
8667
  for (const key of Object.keys(record3)) {
8364
8668
  if (leaves.has(key) || containers.has(key)) continue;
8365
8669
  const child = record3[key];
8366
- if (Array.isArray(child) || isPlainObject18(child)) {
8670
+ if (Array.isArray(child) || isPlainObject19(child)) {
8367
8671
  stripScope(child, currentScope);
8368
8672
  }
8369
8673
  }
@@ -8375,7 +8679,7 @@ var LOGICAL_FILTER_KEYS = /* @__PURE__ */ new Set(["$and", "$or", "$nor"]);
8375
8679
  var isOperatorKey = (key) => key.startsWith("$");
8376
8680
  var REMOVED_VIRTUAL_FILTER = /* @__PURE__ */ Symbol("removed virtual filter clause");
8377
8681
  var rewriteFilterObject = (value, visit) => {
8378
- if (!isPlainObject18(value)) return value;
8682
+ if (!isPlainObject19(value)) return value;
8379
8683
  let changed = false;
8380
8684
  const entries = [];
8381
8685
  for (const [key, child] of Object.entries(value)) {
@@ -8406,7 +8710,7 @@ var resolveVirtualFilterField = (path, scope2) => {
8406
8710
  if (!Object.hasOwn(scope2, segment) || scope2[segment] === void 0) return null;
8407
8711
  const definition = scope2[segment];
8408
8712
  if (!isVirtualContainerValueForGuard(definition)) return REMOVED_VIRTUAL_FILTER;
8409
- scope2 = isPlainObject18(definition.sub) ? definition.sub : null;
8713
+ scope2 = isPlainObject19(definition.sub) ? definition.sub : null;
8410
8714
  inContainer = true;
8411
8715
  }
8412
8716
  return scope2;
@@ -8418,7 +8722,7 @@ var stripVirtualFilterOperator = (key, value, scope2) => {
8418
8722
  }
8419
8723
  if (key === "$all") {
8420
8724
  return rewriteFilterClauses(value, (entry) => {
8421
- if (!isPlainObject18(entry) || Object.keys(entry).length !== 1 || !Object.hasOwn(entry, "$elemMatch")) return entry;
8725
+ if (!isPlainObject19(entry) || Object.keys(entry).length !== 1 || !Object.hasOwn(entry, "$elemMatch")) return entry;
8422
8726
  return rewriteFilterObject(entry, (operator, operand) => stripVirtualFilterOperator(operator, operand, scope2));
8423
8727
  });
8424
8728
  }
@@ -8433,7 +8737,7 @@ var stripVirtualFilterQuery = (value, scope2, element = false) => {
8433
8737
  if (isOperatorKey(key)) return element ? stripVirtualFilterOperator(key, child, scope2) : child;
8434
8738
  const fieldScope = resolveVirtualFilterField(key, scope2);
8435
8739
  if (fieldScope === REMOVED_VIRTUAL_FILTER) return REMOVED_VIRTUAL_FILTER;
8436
- if (!fieldScope || !isPlainObject18(child)) return child;
8740
+ if (!fieldScope || !isPlainObject19(child)) return child;
8437
8741
  if (Object.keys(child).some(isOperatorKey)) {
8438
8742
  return rewriteFilterObject(
8439
8743
  child,
@@ -8457,7 +8761,7 @@ function getCorrelatedTemplateDepth(includes) {
8457
8761
  const visit = (entries, depth) => {
8458
8762
  const list = castArray2(entries).filter(Boolean);
8459
8763
  for (const entry of list) {
8460
- if (!isPlainObject18(entry)) continue;
8764
+ if (!isPlainObject19(entry)) continue;
8461
8765
  max = Math.max(max, depth);
8462
8766
  const nested = entry.args?.include;
8463
8767
  if (nested !== void 0) {
@@ -8486,7 +8790,7 @@ function validateClientFilter(filter2) {
8486
8790
  value.forEach((item, index) => visit(item, `${path}[${index}]`));
8487
8791
  return;
8488
8792
  }
8489
- if (!isPlainObject18(value)) return;
8793
+ if (!isPlainObject19(value)) return;
8490
8794
  Object.entries(value).forEach(([key, child]) => {
8491
8795
  const nextPath = path ? `${path}.${key}` : key;
8492
8796
  if (blockedOperators.has(key)) {
@@ -8768,9 +9072,9 @@ var Base = class {
8768
9072
  const walk = (node, prefix) => {
8769
9073
  for (const [key, value] of Object.entries(node)) {
8770
9074
  if (value === void 0) continue;
8771
- if (isPlainObject18(value) && "sub" in value) {
9075
+ if (isPlainObject19(value) && "sub" in value) {
8772
9076
  const sub = value.sub;
8773
- if (isPlainObject18(sub)) walk(sub, prefix ? `${prefix}.${key}` : key);
9077
+ if (isPlainObject19(sub)) walk(sub, prefix ? `${prefix}.${key}` : key);
8774
9078
  continue;
8775
9079
  }
8776
9080
  out.push(prefix ? `${prefix}.${key}` : key);
@@ -8823,7 +9127,7 @@ var Base = class {
8823
9127
  this.throwClientRequestError("bad_request" /* BadRequest */, `Model ${modelName} not found`);
8824
9128
  }
8825
9129
  for (const entry of entries) {
8826
- if (!isPlainObject18(entry)) continue;
9130
+ if (!isPlainObject19(entry)) continue;
8827
9131
  const models = visited.get(entry) ?? /* @__PURE__ */ new Set();
8828
9132
  if (models.has(modelName)) continue;
8829
9133
  models.add(modelName);
@@ -9442,7 +9746,7 @@ import {
9442
9746
  get as get13,
9443
9747
  isArray as isArray10,
9444
9748
  isBoolean as isBoolean4,
9445
- isPlainObject as isPlainObject25,
9749
+ isPlainObject as isPlainObject26,
9446
9750
  omit,
9447
9751
  set as set10,
9448
9752
  uniq as uniq2,
@@ -9543,7 +9847,7 @@ var model_default = Model;
9543
9847
  // src/acl/distinct-field-authorization.ts
9544
9848
  init_field_authorization();
9545
9849
  init_field_catalog();
9546
- import { isPlainObject as isPlainObject19 } from "@web-ts-toolkit/utils";
9850
+ import { isPlainObject as isPlainObject20 } from "@web-ts-toolkit/utils";
9547
9851
  var schemaVariants = (schema) => Object.values(schema.discriminators ?? {});
9548
9852
  var scalarTypes = /* @__PURE__ */ new Set([
9549
9853
  "String",
@@ -9623,8 +9927,8 @@ function isDistinctFieldAuthorized(args) {
9623
9927
  if (path !== field && !path.startsWith(`${field}.`) && !field.startsWith(`${path}.`)) continue;
9624
9928
  if (path.startsWith(`${field}.`) && (!eligible(path) || !schemaShape(schema, path) || !granted(path)))
9625
9929
  return false;
9626
- if (isPlainObject19(raw) && raw.sub !== void 0) {
9627
- if (!isPlainObject19(raw.sub) || !declaredRulesSafe(raw.sub, path, next)) return false;
9930
+ if (isPlainObject20(raw) && raw.sub !== void 0) {
9931
+ if (!isPlainObject20(raw.sub) || !declaredRulesSafe(raw.sub, path, next)) return false;
9628
9932
  }
9629
9933
  }
9630
9934
  return true;
@@ -9802,7 +10106,7 @@ init_populate_target();
9802
10106
 
9803
10107
  // src/helpers/apply-update.ts
9804
10108
  init_lib();
9805
- import { isPlainObject as isPlainObject23, set as set8 } from "@web-ts-toolkit/utils";
10109
+ import { isPlainObject as isPlainObject24, set as set8 } from "@web-ts-toolkit/utils";
9806
10110
  function applyUpdate(target, data, allowedFields) {
9807
10111
  const wholeFields = /* @__PURE__ */ new Set();
9808
10112
  const partialContainers = /* @__PURE__ */ new Set();
@@ -9822,7 +10126,7 @@ function applyUpdate(target, data, allowedFields) {
9822
10126
  const apply = (values, prefix = "") => {
9823
10127
  for (const [key, value] of Object.entries(values)) {
9824
10128
  const path = prefix ? `${prefix}.${key}` : key;
9825
- if (partialContainers.has(path) && !wholeFields.has(path) && (isPlainObject23(value) || Array.isArray(value))) {
10129
+ if (partialContainers.has(path) && !wholeFields.has(path) && (isPlainObject24(value) || Array.isArray(value))) {
9826
10130
  apply(value, path);
9827
10131
  } else if (isDocument2(target)) {
9828
10132
  target.set(path, value);
@@ -9839,7 +10143,7 @@ init_document();
9839
10143
  init_request_work();
9840
10144
  init_logger_helpers();
9841
10145
  init_request_complexity();
9842
- import { get as get10, isPlainObject as isPlainObject24, set as set9 } from "@web-ts-toolkit/utils";
10146
+ import { get as get10, isPlainObject as isPlainObject25, set as set9 } from "@web-ts-toolkit/utils";
9843
10147
  import { mongo as mongo5 } from "mongoose";
9844
10148
 
9845
10149
  // src/acl/select-resolution.ts
@@ -9956,7 +10260,7 @@ init_field_catalog();
9956
10260
  init_service_authorization();
9957
10261
  var own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
9958
10262
  var inside = (path, root) => path === root || path.startsWith(`${root}.`);
9959
- var record2 = (value) => isPlainObject24(value);
10263
+ var record2 = (value) => isPlainObject25(value);
9960
10264
  function inputValue(value) {
9961
10265
  if (typeof value === "function" || typeof value === "symbol") {
9962
10266
  authorizationError("input values must be persisted data, not functions or symbols");
@@ -11383,7 +11687,7 @@ var Service = class extends Base {
11383
11687
  if (this.isScalarPopulateValue(rawTarget)) return rawTarget;
11384
11688
  const isDoc = (() => {
11385
11689
  try {
11386
- if (isPlainObject25(rawTarget)) return true;
11690
+ if (isPlainObject26(rawTarget)) return true;
11387
11691
  const maybe = rawTarget;
11388
11692
  if (maybe && typeof maybe === "object" && "_doc" in maybe) return true;
11389
11693
  if (maybe && typeof maybe.toObject === "function") return true;
@@ -13786,7 +14090,7 @@ init_helpers();
13786
14090
 
13787
14091
  // src/processors.ts
13788
14092
  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";
14093
+ 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
14094
  function cloneProcessorValue(value) {
13791
14095
  const copy = cloneDeep5(value);
13792
14096
  copyPermissionsAliasGraph(value, copy);
@@ -13826,7 +14130,7 @@ function resolveLeafParents(obj, src) {
13826
14130
  for (let ind = 0; ind < segs.length - 1; ind += 1) {
13827
14131
  const seg = segs[ind];
13828
14132
  targets = targets.reduce((ret, target) => {
13829
- if (!isPlainObject26(target)) return ret;
14133
+ if (!isPlainObject27(target)) return ret;
13830
14134
  const targetObject = target;
13831
14135
  const next = targetObject[seg];
13832
14136
  if (isArray11(next)) {
@@ -13840,7 +14144,7 @@ function resolveLeafParents(obj, src) {
13840
14144
  const leaf = segs[segs.length - 1];
13841
14145
  const pairs = [];
13842
14146
  forEach5(targets, (target) => {
13843
- if (!isPlainObject26(target)) return;
14147
+ if (!isPlainObject27(target)) return;
13844
14148
  pairs.push({ parent: target, leaf });
13845
14149
  });
13846
14150
  return pairs;
@@ -13861,7 +14165,7 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
13861
14165
  forEach5(segs, (seg, ind) => {
13862
14166
  if (segs.length === ind + 1) {
13863
14167
  forEach5(targets, (target) => {
13864
- if (!isPlainObject26(target)) return;
14168
+ if (!isPlainObject27(target)) return;
13865
14169
  const targetObject = target;
13866
14170
  const leaf = targetObject[seg];
13867
14171
  const sourceForDest = leaf;
@@ -13869,7 +14173,7 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
13869
14173
  if (isArray11(leaf)) {
13870
14174
  if (leaf.length === 0) {
13871
14175
  depopulated = [];
13872
- } else if (leaf.every((item) => isPlainObject26(item))) {
14176
+ } else if (leaf.every((item) => isPlainObject27(item))) {
13873
14177
  depopulated = map(leaf, idField).map((id, i) => {
13874
14178
  if (id === void 0) {
13875
14179
  failMissingId(`${src}[${i}]`);
@@ -13879,7 +14183,7 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
13879
14183
  } else {
13880
14184
  return;
13881
14185
  }
13882
- } else if (isPlainObject26(leaf)) {
14186
+ } else if (isPlainObject27(leaf)) {
13883
14187
  const id = get14(leaf, idField);
13884
14188
  if (id === void 0) {
13885
14189
  failMissingId(src);
@@ -13893,7 +14197,7 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
13893
14197
  });
13894
14198
  } else {
13895
14199
  targets = targets.reduce((ret, target) => {
13896
- if (!isPlainObject26(target)) return ret;
14200
+ if (!isPlainObject27(target)) return ret;
13897
14201
  const targetObject = target;
13898
14202
  const next = targetObject[seg];
13899
14203
  if (isArray11(next)) {
@@ -13999,7 +14303,7 @@ var countPaths = (docObject, operations, options = { mutable: true }) => {
13999
14303
  let count;
14000
14304
  if (isArray11(leafValue)) {
14001
14305
  count = leafValue.length;
14002
- } else if (isPlainObject26(leafValue)) {
14306
+ } else if (isPlainObject27(leafValue)) {
14003
14307
  count = Object.keys(leafValue).length;
14004
14308
  } else if (leafValue === null || typeof leafValue === "undefined") {
14005
14309
  count = 0;
@@ -14641,12 +14945,12 @@ function guard(condition) {
14641
14945
  const permissions = req[PERMISSIONS];
14642
14946
  let cond = condition;
14643
14947
  let phas = (key) => permissions.has(key);
14644
- if (isPlainObject27(condition)) {
14948
+ if (isPlainObject28(condition)) {
14645
14949
  const { modelName, id, condition: _cond } = condition;
14646
14950
  const svc = req.macl.getPublicService(modelName);
14647
14951
  const select = getModelOption(modelName, `alwaysSelectFields.read`, void 0);
14648
14952
  let _id = isString7(id) ? id : null;
14649
- if (isPlainObject27(id)) {
14953
+ if (isPlainObject28(id)) {
14650
14954
  const { type = "param", key } = id;
14651
14955
  if (type === "param") {
14652
14956
  const paramValue = req.params[key];
@@ -14688,7 +14992,7 @@ import express2 from "express";
14688
14992
 
14689
14993
  // src/routers/model-router.ts
14690
14994
  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";
14995
+ import { forEach as forEach7, isPlainObject as isPlainObject30, isString as isString8, isUndefined as isUndefined2, normalizeUrlPath as normalizeUrlPath3, padEnd } from "@web-ts-toolkit/utils";
14692
14996
  init_logger_helpers();
14693
14997
  init_runtime();
14694
14998
  init_runtime_context();
@@ -14822,7 +15126,7 @@ import JsonRouter7 from "@web-ts-toolkit/express-json-router";
14822
15126
 
14823
15127
  // src/validation/common.ts
14824
15128
  import { z as z2 } from "zod";
14825
- import { isPlainObject as isPlainObject28 } from "@web-ts-toolkit/utils";
15129
+ import { isPlainObject as isPlainObject29 } from "@web-ts-toolkit/utils";
14826
15130
 
14827
15131
  // src/validation/public-admission-schema.ts
14828
15132
  init_public_admission();
@@ -14951,7 +15255,7 @@ var correlatedFilterSchema = z2.record(z2.string(), z2.unknown()).superRefine((f
14951
15255
  }
14952
15256
  });
14953
15257
  var correlatedEmptyOptionsSchema = z2.unknown().refine(
14954
- (value) => value === void 0 || isPlainObject28(value) && Object.keys(value).length === 0,
15258
+ (value) => value === void 0 || isPlainObject29(value) && Object.keys(value).length === 0,
14955
15259
  "Correlated include options must be absent or empty"
14956
15260
  ).optional();
14957
15261
  var correlatedPathSchema = z2.string().min(1).superRefine((path, ctx) => {
@@ -14988,7 +15292,7 @@ var correlatedListArgsSchema = z2.object({
14988
15292
  include: z2.lazy(() => correlatedNestedIncludeSchema).optional()
14989
15293
  }).strict().superRefine((args, ctx) => checkArgsMarkers(args.select, args.sort, ctx));
14990
15294
  var correlatedCountArgsSchema = z2.unknown().refine(
14991
- (value) => value === void 0 || isPlainObject28(value) && Object.keys(value).length === 0,
15295
+ (value) => value === void 0 || isPlainObject29(value) && Object.keys(value).length === 0,
14992
15296
  "Count includes accept no args"
14993
15297
  ).optional();
14994
15298
  var correlatedReadByIdSchema = z2.object({
@@ -15041,7 +15345,7 @@ var correlatedNestedIncludeSchema = z2.union([includeItemSchema, z2.array(includ
15041
15345
  var rejectDuplicateCorrelatedPaths = (items, ctx) => {
15042
15346
  const seen = /* @__PURE__ */ new Set();
15043
15347
  items.forEach((item, index) => {
15044
- if (isPlainObject28(item) && item.mode === "correlated" && typeof item.path === "string") {
15348
+ if (isPlainObject29(item) && item.mode === "correlated" && typeof item.path === "string") {
15045
15349
  if (seen.has(item.path)) {
15046
15350
  ctx.addIssue({
15047
15351
  code: z2.ZodIssueCode.custom,
@@ -17042,7 +17346,7 @@ var ModelRouter = class _ModelRouter {
17042
17346
  value
17043
17347
  );
17044
17348
  }
17045
- if (arguments.length === 1 && isPlainObject29(keyOrOptions)) {
17349
+ if (arguments.length === 1 && isPlainObject30(keyOrOptions)) {
17046
17350
  assertMutableRouterOptions("model", keyOrOptions);
17047
17351
  this.runtime.setModelOptions(
17048
17352
  this.modelName,
@@ -17576,7 +17880,7 @@ var RootRouter = class {
17576
17880
 
17577
17881
  // src/routers/data-router.ts
17578
17882
  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";
17883
+ import { isPlainObject as isPlainObject31, isString as isString9, isUndefined as isUndefined3, normalizeUrlPath as normalizeUrlPath5 } from "@web-ts-toolkit/utils";
17580
17884
  init_runtime();
17581
17885
  init_helpers();
17582
17886
  init_schemas();
@@ -17792,7 +18096,7 @@ var DataRouter = class {
17792
18096
  value
17793
18097
  );
17794
18098
  }
17795
- if (arguments.length === 1 && isPlainObject30(keyOrOptions)) {
18099
+ if (arguments.length === 1 && isPlainObject31(keyOrOptions)) {
17796
18100
  assertMutableRouterOptions("data", keyOrOptions);
17797
18101
  this.runtime.setDataOptions(this.dataName, keyOrOptions);
17798
18102
  }
@@ -17951,7 +18255,7 @@ function createRuntimeApi(runtime) {
17951
18255
  if (arguments.length === 2 && isString10(keyOrOptions)) {
17952
18256
  return runtime.setGlobalOption(keyOrOptions, value);
17953
18257
  }
17954
- if (arguments.length === 1 && isPlainObject31(keyOrOptions)) {
18258
+ if (arguments.length === 1 && isPlainObject32(keyOrOptions)) {
17955
18259
  return runtime.setGlobalOptions(keyOrOptions);
17956
18260
  }
17957
18261
  };