@web-ts-toolkit/access-router 0.57.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 +1563 -947
  2. package/index.mjs +1375 -760
  3. package/package.json +3 -3
package/index.mjs CHANGED
@@ -3534,6 +3534,47 @@ function serviceAuthorizationInput(policy, targets) {
3534
3534
  }
3535
3535
  return { rows: policy.rows, outputFields: policy.outputFields, related };
3536
3536
  }
3537
+ function hasStableConfigurationCopies(value) {
3538
+ if (value === null || typeof value !== "object") return true;
3539
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) return false;
3540
+ return Object.values(value).every(hasStableConfigurationCopies);
3541
+ }
3542
+ function captureAuthorizationAccess(value) {
3543
+ const input = authorizationRecord(value, "access");
3544
+ const access = {};
3545
+ for (const key of ["operation", "rowAccess", "virtualAccess", "outputAccess", "docPermissionsAccess"]) {
3546
+ if (key === "rowAccess" && input[key] === void 0) continue;
3547
+ if (typeof input[key] !== "string") authorizationError(`invalid access.${key}`);
3548
+ access[key] = input[key];
3549
+ }
3550
+ return Object.freeze(access);
3551
+ }
3552
+ function captureAuthorizationCatalog(value) {
3553
+ const input = authorizationRecord(value, "catalog");
3554
+ const catalog = {};
3555
+ for (const key of [
3556
+ "paths",
3557
+ "persistedPaths",
3558
+ "arrayPaths",
3559
+ "schemaVirtualPaths",
3560
+ "metadataPaths",
3561
+ "dynamicPaths",
3562
+ "containerPaths",
3563
+ "virtualPaths",
3564
+ "virtualScopePaths",
3565
+ "opaquePaths",
3566
+ "referencePaths",
3567
+ "protectedPaths"
3568
+ ]) {
3569
+ const paths = input[key];
3570
+ if (key !== "paths" && paths === void 0) continue;
3571
+ if (!Array.isArray(paths) || Array.from(paths).some((path) => typeof path !== "string")) {
3572
+ authorizationError(`invalid catalog.${key}`);
3573
+ }
3574
+ catalog[key] = paths;
3575
+ }
3576
+ return Object.freeze(catalog);
3577
+ }
3537
3578
  function assertAuthorizationPath(path) {
3538
3579
  if (typeof path !== "string" || !isSafeOutputPath(path)) {
3539
3580
  authorizationError(`invalid response path: ${String(path)}`);
@@ -3663,6 +3704,9 @@ function resolveServiceAuthorization(input) {
3663
3704
  const raw = copyAuthorizationValue(input.authorization);
3664
3705
  const configuration = copyAuthorizationValue(input.configuration, true);
3665
3706
  const targets = copyAuthorizationValue(input.relatedTargets ?? [], true);
3707
+ const access = copyAuthorizationValue(input.access);
3708
+ const outputAccess = captureAuthorizationAccess(access);
3709
+ const catalog = captureAuthorizationCatalog(configuration.catalog);
3666
3710
  const policy = copyAuthorizationValue(normalizePolicy(raw, input.applicability ?? "service", configuration, targets));
3667
3711
  const scopePath = Array.from(scope(input.binding));
3668
3712
  for (const part of scopePath) {
@@ -3675,17 +3719,21 @@ function resolveServiceAuthorization(input) {
3675
3719
  authorizationError("derived call request/runtime mismatch");
3676
3720
  }
3677
3721
  }
3678
- const permissions = Object.fromEntries(
3679
- input.requestPermissions.keys.map((key) => [key, input.requestPermissions.has(key)])
3722
+ const permissions = new permission_default(
3723
+ Object.fromEntries(input.requestPermissions.keys.map((key) => [key, input.requestPermissions.has(key) === true]))
3680
3724
  );
3725
+ for (const value of Object.values(permissions)) if (value && typeof value === "object") Object.freeze(value);
3726
+ Object.freeze(permissions);
3681
3727
  const call = Object.freeze(/* @__PURE__ */ Object.create(null));
3682
3728
  calls.set(call, {
3683
3729
  binding: Object.freeze({ ...input.binding, scopePath: Object.freeze(scopePath) }),
3684
- access: copyAuthorizationValue(input.access),
3730
+ access,
3685
3731
  configuration,
3686
3732
  policy,
3687
3733
  relatedTargets: targets,
3688
- permissions: Object.freeze(permissions),
3734
+ // normalizeFields constructs only mode strings and validated string paths.
3735
+ output: Object.freeze({ access: outputAccess, catalog, outputFields: policy.outputFields }),
3736
+ permissions,
3689
3737
  provenance: input.parent ? callRecord(input.parent).provenance : call
3690
3738
  });
3691
3739
  return call;
@@ -3703,12 +3751,84 @@ function readServiceAuthorization(call, binding) {
3703
3751
  true
3704
3752
  );
3705
3753
  }
3754
+ function readServiceAuthorizationAccess(call, binding) {
3755
+ assertAuthorizationBinding(call, binding);
3756
+ return callRecord(call).output.access;
3757
+ }
3758
+ function readServiceAuthorizationHydration(call, binding) {
3759
+ assertAuthorizationBinding(call, binding);
3760
+ return copyAuthorizationValue({ hydration: callRecord(call).configuration.hydration }, true);
3761
+ }
3762
+ function outputMetadata(configuration) {
3763
+ return {
3764
+ documentPermissionField: configuration.documentPermissionField,
3765
+ exposedDocPermissionKeys: configuration.exposedDocPermissionKeys,
3766
+ stripPermissionsField: configuration.stripPermissionsField,
3767
+ disableFieldPermissions: configuration.disableFieldPermissions
3768
+ };
3769
+ }
3770
+ function readServiceOutputMetadata(call, binding) {
3771
+ assertAuthorizationBinding(call, binding);
3772
+ return copyAuthorizationValue(outputMetadata(callRecord(call).configuration), true);
3773
+ }
3774
+ function readServiceDocumentPermissions(call, binding) {
3775
+ assertAuthorizationBinding(call, binding);
3776
+ const record3 = callRecord(call);
3777
+ return Object.freeze({
3778
+ catalog: record3.output.catalog,
3779
+ ...copyAuthorizationValue({ docPermissions: record3.configuration.docPermissions }, true)
3780
+ });
3781
+ }
3782
+ function readServiceFinalizerConfiguration(call, binding) {
3783
+ assertAuthorizationBinding(call, binding);
3784
+ const record3 = callRecord(call);
3785
+ return Object.freeze({
3786
+ catalog: record3.output.catalog,
3787
+ ...copyAuthorizationValue(
3788
+ {
3789
+ ...outputMetadata(record3.configuration),
3790
+ virtuals: record3.configuration.virtuals,
3791
+ docPermissions: record3.configuration.docPermissions
3792
+ },
3793
+ true
3794
+ )
3795
+ });
3796
+ }
3797
+ function readServiceOutputPolicy(call, binding) {
3798
+ assertAuthorizationBinding(call, binding);
3799
+ return callRecord(call).output;
3800
+ }
3801
+ function readServiceOutputFieldAuthorization(call, binding) {
3802
+ assertAuthorizationBinding(call, binding);
3803
+ const record3 = callRecord(call);
3804
+ const reusable = reusableOutputFieldConfiguration(record3);
3805
+ return Object.freeze({
3806
+ access: record3.output.access,
3807
+ catalog: record3.output.catalog,
3808
+ outputFields: record3.output.outputFields,
3809
+ reusable,
3810
+ ...copyAuthorizationValue(
3811
+ {
3812
+ permissionSchema: record3.configuration.permissionSchema,
3813
+ modelPermissionPrefix: record3.configuration.modelPermissionPrefix
3814
+ },
3815
+ true
3816
+ )
3817
+ });
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
+ }
3706
3829
  function getAuthorizationPermissions(call, binding) {
3707
3830
  assertAuthorizationBinding(call, binding);
3708
- const permission = new permission_default({ ...callRecord(call).permissions });
3709
- for (const value of Object.values(permission)) if (value && typeof value === "object") Object.freeze(value);
3710
- Object.freeze(permission);
3711
- return permission;
3831
+ return callRecord(call).permissions;
3712
3832
  }
3713
3833
  function getAuthorizationProvenance(call) {
3714
3834
  return callRecord(call).provenance;
@@ -3724,399 +3844,87 @@ var init_service_authorization = __esm({
3724
3844
  }
3725
3845
  });
3726
3846
 
3727
- // src/acl/document-authorization.ts
3728
- import { Document as Document3 } from "mongoose";
3729
- function normalizeOutputAuthorizationOptions(input, options, purpose) {
3730
- const value = authorizationRecord(options, "output options");
3731
- for (const key of Reflect.ownKeys(value)) {
3732
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
3733
- if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable) {
3734
- authorizationError("invalid output option property");
3735
- }
3736
- }
3737
- assertAuthorizationKeys(
3738
- value,
3739
- ["authorization", "scopePath", "documentAuthorization", ...purpose ? ["purpose"] : []],
3740
- "output options"
3741
- );
3742
- if (purpose && value.purpose !== purpose) authorizationError("genAllowedFields requires purpose: output");
3743
- if (Object.prototype.hasOwnProperty.call(value, "documentAuthorization")) {
3744
- if (Object.prototype.hasOwnProperty.call(value, "authorization") || Object.prototype.hasOwnProperty.call(value, "scopePath")) {
3745
- authorizationError("document handle cannot be mixed with raw policy/scope");
3746
- }
3747
- const handle = value.documentAuthorization;
3748
- const stage = stageRecord(documentRecord(handle).stage);
3749
- const binding = Object.freeze({ ...input.binding, scopePath: stage.binding.scopePath });
3750
- assertAuthorizationBinding(stage.call, binding);
3751
- const access = readServiceAuthorization(stage.call, binding).access;
3752
- if (input.access.outputAccess !== access.outputAccess) authorizationError("document access mismatch");
3753
- return Object.freeze({ kind: "document", documentAuthorization: handle, binding });
3754
- }
3755
- if (value.scopePath !== void 0 && !Array.isArray(value.scopePath))
3756
- authorizationError("scopePath must be an array");
3757
- return Object.freeze({
3758
- kind: "policy",
3759
- authorization: resolveServiceAuthorization({
3760
- ...input,
3761
- binding: {
3762
- ...input.binding,
3763
- scopePath: copyAuthorizationValue(value.scopePath)
3764
- },
3765
- authorization: value.authorization,
3766
- applicability: "output"
3767
- })
3768
- });
3769
- }
3770
- function stageRecord(stage) {
3771
- const record3 = stages.get(stage);
3772
- if (!record3) authorizationError("invalid document stage");
3773
- if (!matchesAuthorizationSnapshot(record3.input, record3.snapshot)) authorizationError("changed document snapshot");
3774
- return record3;
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;
3775
3852
  }
3776
- function documentRecord(handle) {
3777
- const record3 = documents.get(handle);
3778
- if (!record3) authorizationError("invalid document handle");
3779
- stageRecord(record3.stage);
3780
- return record3;
3853
+ function extractOutputFieldRules(schema, path, access) {
3854
+ return extractOutputFieldRuleEntries(schema, path, access).map((entry) => entry.rule);
3781
3855
  }
3782
- function createDocumentAuthorizationStage(call, binding, projectedSnapshot) {
3783
- assertAuthorizationBinding(call, binding);
3784
- authorizationRecord(projectedSnapshot, "projected document snapshot");
3785
- const stage = Object.freeze(/* @__PURE__ */ Object.create(null));
3786
- stages.set(stage, {
3787
- call,
3788
- binding: Object.freeze({ ...binding, scopePath: Object.freeze([...binding.scopePath ?? []]) }),
3789
- input: projectedSnapshot,
3790
- snapshot: copyAuthorizationValue(projectedSnapshot, "document")
3791
- });
3792
- return stage;
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}.`)];
3793
3866
  }
3794
- function assertDocumentAuthorizationStage(stage, call, binding, projectedSnapshot) {
3795
- const record3 = stageRecord(stage);
3796
- assertAuthorizationBinding(record3.call, binding);
3797
- if (record3.call !== call || record3.input !== projectedSnapshot || !matchesAuthorizationSnapshot(projectedSnapshot, record3.snapshot)) {
3798
- authorizationError("document call/stage/snapshot mismatch");
3799
- }
3867
+ function hasExplicitFieldGrant(policy, path) {
3868
+ return policy?.mode === "unrestricted" || policy?.mode === "grant" && policy.paths.some((grant) => path === grant || path.startsWith(`${grant}.`));
3800
3869
  }
3801
- function resolveDocumentAuthorization(stage, resolveGrants) {
3802
- const record3 = stageRecord(stage);
3803
- if (!record3.result) {
3804
- record3.result = Promise.resolve().then(async () => {
3805
- stageRecord(stage);
3806
- const result2 = resolveGrants.call(
3807
- record3.binding.request,
3808
- copyAuthorizationValue(record3.snapshot, "document"),
3809
- getAuthorizationPermissions(record3.call, record3.binding)
3810
- );
3811
- const grants = result2 && typeof result2.then === "function" ? await result2 : result2;
3812
- stageRecord(stage);
3813
- const ownedGrants = copyAuthorizationValue(authorizationRecord(grants, "document grants"));
3814
- const handle = Object.freeze(/* @__PURE__ */ Object.create(null));
3815
- documents.set(handle, { stage, grants: ownedGrants, decisions: /* @__PURE__ */ new Map() });
3816
- return handle;
3817
- });
3818
- }
3819
- return record3.result;
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";
3820
3880
  }
3821
- function readDocumentAuthorization(handle, binding) {
3822
- const record3 = documentRecord(handle);
3823
- const stage = stageRecord(record3.stage);
3824
- assertAuthorizationBinding(stage.call, binding);
3825
- return Object.freeze({
3826
- authorization: stage.call,
3827
- stage: record3.stage,
3828
- grants: copyAuthorizationValue(record3.grants),
3829
- ...readServiceAuthorization(stage.call, binding).access
3830
- });
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" });
3831
3885
  }
3832
- function memoizeDocumentFieldDecision(handle, binding, field, evaluate) {
3833
- const record3 = documentRecord(handle);
3834
- const stage = stageRecord(record3.stage);
3835
- assertAuthorizationBinding(stage.call, binding);
3836
- let decision = record3.decisions.get(field);
3837
- if (!decision) {
3838
- decision = Promise.resolve().then(async () => {
3839
- stageRecord(record3.stage);
3840
- const result2 = await evaluate.call(
3841
- stage.binding.request,
3842
- getAuthorizationPermissions(stage.call, binding),
3843
- copyAuthorizationValue(record3.grants)
3844
- );
3845
- stageRecord(record3.stage);
3846
- if (typeof result2 !== "boolean") authorizationError("field decision must be boolean");
3847
- return result2;
3848
- });
3849
- record3.decisions.set(field, decision);
3850
- }
3851
- return decision;
3886
+ function combineFieldAuthorizationStates(states2) {
3887
+ return states2.includes("denied") ? "denied" : states2.includes("deferred") ? "deferred" : "granted";
3852
3888
  }
3853
- function unchangedOutput(output, record3) {
3854
- if (!matchesAuthorizationSnapshot(output, record3.snapshot)) return false;
3855
- const identities = outputIdentities(output);
3856
- return identities.length === record3.identities.length && identities.every((identity, i) => identity === record3.identities[i]);
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);
3857
3895
  }
3858
- function assertDocumentAuthorization(handle, use) {
3859
- const record3 = documentRecord(handle);
3860
- const stage = stageRecord(record3.stage);
3861
- assertAuthorizationBinding(stage.call, use.binding);
3862
- if (use.authorization !== void 0 && stage.call !== use.authorization || use.stage !== void 0 && record3.stage !== use.stage || readServiceAuthorization(stage.call, use.binding).access.outputAccess !== use.outputAccess) {
3863
- authorizationError("document call/access/stage mismatch");
3864
- }
3865
- const association = outputs.get(use.output);
3866
- if (!association || association.handle !== handle || !unchangedOutput(use.output, association)) {
3867
- authorizationError("unknown, replaced or mutated authorized output");
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
+ }
3868
3918
  }
3919
+ return false;
3869
3920
  }
3870
- function associateDocumentAuthorization(handle, binding, output) {
3871
- const record3 = documentRecord(handle);
3872
- assertAuthorizationBinding(stageRecord(record3.stage).call, binding);
3873
- if (!output || typeof output !== "object") authorizationError("output must be an object");
3874
- if (outputs.has(output)) {
3875
- const previous = outputs.get(output);
3876
- if (previous.handle !== handle || !unchangedOutput(output, previous))
3877
- authorizationError("output already associated");
3878
- return;
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;
3879
3926
  }
3880
- outputs.set(output, {
3881
- handle,
3882
- snapshot: copyAuthorizationValue(output, "document"),
3883
- identities: outputIdentities(output)
3884
- });
3885
- }
3886
- function transferDocumentAuthorization(handle, use, copy) {
3887
- assertDocumentAuthorization(handle, use);
3888
- associateDocumentAuthorization(handle, use.binding, copy);
3889
- }
3890
- function isKnownAuthorizationOutput(output) {
3891
- return outputs.has(output);
3892
- }
3893
- function getAssociatedDocumentAuthorization(output, call) {
3894
- const record3 = outputs.get(output);
3895
- if (!record3 || !unchangedOutput(output, record3)) return void 0;
3896
- const stage = stageRecord(documentRecord(record3.handle).stage);
3897
- if (call && getAuthorizationProvenance(stage.call) !== getAuthorizationProvenance(call)) return void 0;
3898
- return record3.handle;
3899
- }
3900
- function transferDocumentAuthorizationGraph(source, copy, copyOrigins) {
3901
- const seen = /* @__PURE__ */ new WeakSet();
3902
- const visit = (source2, copy2) => {
3903
- if (!copy2 || typeof copy2 !== "object" || seen.has(copy2)) return;
3904
- seen.add(copy2);
3905
- source2 = copyOrigins?.get(copy2) ?? source2;
3906
- if (source2 instanceof Document3) source2 = source2._doc;
3907
- const original = source2 && typeof source2 === "object" ? source2 : void 0;
3908
- if (!original && !copyOrigins) return;
3909
- const association = original && outputs.get(original);
3910
- if (association) {
3911
- const stage = stageRecord(documentRecord(association.handle).stage);
3912
- transferDocumentAuthorization(
3913
- association.handle,
3914
- {
3915
- binding: stage.binding,
3916
- output: original,
3917
- outputAccess: readServiceAuthorization(stage.call, stage.binding).access.outputAccess,
3918
- authorization: stage.call,
3919
- stage: documentRecord(association.handle).stage
3920
- },
3921
- copy2
3922
- );
3923
- }
3924
- for (const key of Object.keys(copy2)) {
3925
- const descriptor = original && Object.getOwnPropertyDescriptor(original, key);
3926
- if (descriptor && "value" in descriptor) {
3927
- visit(descriptor.value, copy2[key]);
3928
- } else if (copyOrigins) {
3929
- visit(void 0, copy2[key]);
3930
- }
3931
- }
3932
- };
3933
- visit(source, copy);
3934
- }
3935
- function createServiceOutputContext(diagnostic, handle, use) {
3936
- assertDocumentAuthorization(handle, use);
3937
- const rootOutput = use.output;
3938
- const root = outputs.get(rootOutput);
3939
- const graph = new Set(root.identities);
3940
- const call = stageRecord(documentRecord(handle).stage).call;
3941
- const context = { ...diagnostic };
3942
- Object.defineProperties(context, {
3943
- documentAuthorization: { value: handle, enumerable: false, writable: false, configurable: false },
3944
- getDocumentAuthorization: {
3945
- enumerable: false,
3946
- writable: false,
3947
- configurable: false,
3948
- value(output) {
3949
- if (!graph.has(output) || !unchangedOutput(rootOutput, root)) return void 0;
3950
- const association = outputs.get(output);
3951
- if (!association || !unchangedOutput(output, association)) return void 0;
3952
- try {
3953
- documentRecord(handle);
3954
- const child = stageRecord(documentRecord(association.handle).stage);
3955
- if (getAuthorizationProvenance(child.call) !== getAuthorizationProvenance(call)) return void 0;
3956
- return association.handle;
3957
- } catch {
3958
- return void 0;
3959
- }
3960
- }
3961
- }
3962
- });
3963
- return context;
3964
- }
3965
- var stages, documents, outputs;
3966
- var init_document_authorization = __esm({
3967
- "src/acl/document-authorization.ts"() {
3968
- init_service_authorization();
3969
- init_authorization_snapshot();
3970
- stages = /* @__PURE__ */ new WeakMap();
3971
- documents = /* @__PURE__ */ new WeakMap();
3972
- outputs = /* @__PURE__ */ new WeakMap();
3973
- }
3974
- });
3975
-
3976
- // src/output/include-output.ts
3977
- import { set as set5 } from "@web-ts-toolkit/utils";
3978
- function prepareIncludeOutput(doc) {
3979
- if (stateFor(doc)) return doc;
3980
- const source = isolateDocForOutput(doc);
3981
- transferDocumentAuthorizationGraph(doc, source);
3982
- const working = deepIsolateValue(source);
3983
- outputs2.set(working, { original: doc, source, attachments: [] });
3984
- return working;
3985
- }
3986
- function attachIncludeOutput(doc, path, value) {
3987
- const state = stateFor(doc);
3988
- if (!state) throw new Error("Include attachment requires a prepared output row");
3989
- state.attachments.push({ path, value });
3990
- set5(doc, path, deepIsolateValue(value));
3991
- }
3992
- function getIncludeSource(doc) {
3993
- return stateFor(doc)?.source ?? doc;
3994
- }
3995
- function getIncludeOriginal(doc) {
3996
- return stateFor(doc)?.original ?? doc;
3997
- }
3998
- function restoreIncludeOutput(doc, output) {
3999
- const attachments = stateFor(doc)?.attachments;
4000
- if (!attachments?.length) return void 0;
4001
- const origins = /* @__PURE__ */ new WeakMap();
4002
- for (const { path, value } of attachments) {
4003
- const copy = deepIsolateValue(value);
4004
- if (copy !== null && typeof copy === "object") origins.set(copy, value);
4005
- set5(output, path, copy);
4006
- }
4007
- return origins;
4008
- }
4009
- var outputs2, stateFor;
4010
- var init_include_output = __esm({
4011
- "src/output/include-output.ts"() {
4012
- init_document_authorization();
4013
- init_document();
4014
- outputs2 = /* @__PURE__ */ new WeakMap();
4015
- stateFor = (doc) => doc !== null && typeof doc === "object" ? outputs2.get(doc) : void 0;
4016
- }
4017
- });
4018
-
4019
- // src/helpers/request-work.ts
4020
- function getRequestWorkState(req, runtime) {
4021
- let owners = states.get(req);
4022
- if (!owners) {
4023
- owners = /* @__PURE__ */ new WeakMap();
4024
- states.set(req, owners);
4025
- }
4026
- let state = owners.get(runtime);
4027
- if (!state) {
4028
- const limits = resolveRequestComplexity(runtime.getGlobalOption("requestComplexity"));
4029
- state = {
4030
- totalQueries: 0,
4031
- scheduler: new RequestConcurrencyScheduler(limits.maxBulkConcurrency),
4032
- hookGate: new SharedHookGate(limits.maxHookConcurrency)
4033
- };
4034
- owners.set(runtime, state);
4035
- }
4036
- return state;
4037
- }
4038
- var states;
4039
- var init_request_work = __esm({
4040
- "src/helpers/request-work.ts"() {
4041
- init_request_complexity();
4042
- init_concurrency();
4043
- states = /* @__PURE__ */ new WeakMap();
4044
- }
4045
- });
4046
-
4047
- // src/acl/field-authorization.ts
4048
- function extractScopedOutputRule(schema, field, access) {
4049
- if (!schema || !Object.prototype.hasOwnProperty.call(schema, field)) return void 0;
4050
- const raw = schema[field];
4051
- return raw && typeof raw === "object" && !Array.isArray(raw) && Object.prototype.hasOwnProperty.call(raw, access) ? raw[access] : raw;
4052
- }
4053
- function extractOutputFieldRules(schema, path, access) {
4054
- return extractOutputFieldRuleEntries(schema, path, access).map((entry) => entry.rule);
4055
- }
4056
- function extractOutputFieldRuleEntries(schema, path, access, prefix = "") {
4057
- if (!schema) return [{ path: `${prefix}${path}`, rule: void 0 }];
4058
- if (Object.prototype.hasOwnProperty.call(schema, path))
4059
- return [{ path: `${prefix}${path}`, rule: extractScopedOutputRule(schema, path, access) }];
4060
- const [head, ...rest] = path.split(".");
4061
- const rule = extractScopedOutputRule(schema, head, access);
4062
- const raw = schema[head];
4063
- const entry = { path: `${prefix}${head}`, rule };
4064
- if (!rest.length || !raw?.sub) return [entry];
4065
- return [entry, ...extractOutputFieldRuleEntries(raw.sub, rest.join("."), access, `${prefix}${head}.`)];
4066
- }
4067
- function hasExplicitFieldGrant(policy, path) {
4068
- return policy?.mode === "unrestricted" || policy?.mode === "grant" && policy.paths.some((grant) => path === grant || path.startsWith(`${grant}.`));
4069
- }
4070
- function classifyRequestFieldRule(rule, permissions, modelPermissionPrefix = "") {
4071
- if (typeof rule === "boolean") return rule ? "granted" : "denied";
4072
- if (typeof rule === "function") return "deferred";
4073
- const validator = createValidator((key) => permissions.has(key));
4074
- if (typeof rule !== "string" && !Array.isArray(rule)) return "denied";
4075
- if (typeof rule === "string" ? validator.stringHandler(rule) : validator.arrayHandler(rule)) return "granted";
4076
- const possible = createValidator(
4077
- (key) => permissions.has(key) || !modelPermissionPrefix || key.startsWith(modelPermissionPrefix)
4078
- );
4079
- return (typeof rule === "string" ? possible.stringHandler(rule) : possible.arrayHandler(rule)) ? "deferred" : "denied";
4080
- }
4081
- function classifyEffectiveFieldAuthorization(args) {
4082
- if (hasExplicitFieldGrant(args.outputFields, args.path)) return "granted";
4083
- const states2 = args.rules.map(
4084
- (rule) => classifyRequestFieldRule(rule, args.globalPermissions, args.modelPermissionPrefix)
4085
- );
4086
- return states2.includes("denied") ? "denied" : states2.includes("deferred") ? "deferred" : "granted";
4087
- }
4088
- async function evaluateScopedAccessRule(args) {
4089
- const { req, rule, globalPermissions, docPermissions, modelPermissionPrefix } = args;
4090
- if (typeof rule === "boolean") return rule;
4091
- const validator = createValidator((key) => {
4092
- try {
4093
- if (globalPermissions?.has(key)) return true;
4094
- } catch {
4095
- }
4096
- try {
4097
- return Boolean((docPermissions ?? {})[stripModelPermissionPrefix(key, modelPermissionPrefix)]);
4098
- } catch {
4099
- return false;
4100
- }
4101
- });
4102
- if (typeof rule === "string") return validator.stringHandler(rule);
4103
- if (Array.isArray(rule)) return validator.arrayHandler(rule);
4104
- if (typeof rule === "function") {
4105
- try {
4106
- return Boolean(await rule.call(req, globalPermissions, docPermissions));
4107
- } catch {
4108
- return false;
4109
- }
4110
- }
4111
- return false;
4112
- }
4113
- async function evaluateEffectiveFieldAuthorization(args) {
4114
- if (hasExplicitFieldGrant(args.outputFields, args.path)) return true;
4115
- for (const [index, rule] of args.rules.entries()) {
4116
- if (!await (args.evaluateRule ? args.evaluateRule(rule, index) : evaluateScopedAccessRule({ ...args, rule })))
4117
- return false;
4118
- }
4119
- return true;
3927
+ return true;
4120
3928
  }
4121
3929
  var stripModelPermissionPrefix;
4122
3930
  var init_field_authorization = __esm({
@@ -4127,7 +3935,7 @@ var init_field_authorization = __esm({
4127
3935
  });
4128
3936
 
4129
3937
  // src/acl/virtual-projection.ts
4130
- 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";
4131
3939
  function planVirtualProjection(args) {
4132
3940
  if (args.snapshot.catalog) return planCatalogProjection(args);
4133
3941
  const {
@@ -4361,20 +4169,20 @@ var init_virtual_projection = __esm({
4361
4169
  init_virtual_populate_dependencies();
4362
4170
  init_virtual_descriptor();
4363
4171
  getScopedPermissionSchema = (root, scopePath) => {
4364
- if (!root || !isPlainObject16(root)) return null;
4172
+ if (!root || !isPlainObject15(root)) return null;
4365
4173
  if (scopePath.length === 0) return root;
4366
4174
  const scoped = get6(root, scopePath.join("."));
4367
- return isPlainObject16(scoped) ? scoped : null;
4175
+ return isPlainObject15(scoped) ? scoped : null;
4368
4176
  };
4369
4177
  resolveAlwaysSelectForAccess = (raw, access) => {
4370
4178
  if (!raw) return [];
4371
- if (isArray7(raw)) return [...raw];
4372
- if (isPlainObject16(raw)) {
4179
+ if (isArray6(raw)) return [...raw];
4180
+ if (isPlainObject15(raw)) {
4373
4181
  const record3 = raw;
4374
4182
  const exact = record3[access];
4375
- if (isArray7(exact)) return [...exact];
4183
+ if (isArray6(exact)) return [...exact];
4376
4184
  const def = record3.default;
4377
- if (isArray7(def)) return [...def];
4185
+ if (isArray6(def)) return [...def];
4378
4186
  return [];
4379
4187
  }
4380
4188
  return [];
@@ -4399,6 +4207,35 @@ var init_virtual_projection = __esm({
4399
4207
  });
4400
4208
 
4401
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
+ }
4402
4239
  function compactPersistedProjection(paths) {
4403
4240
  const unique = [...new Set(paths.filter((p) => p && !p.startsWith("-")))];
4404
4241
  return unique.filter((path) => !unique.some((parent) => parent !== path && path.startsWith(`${parent}.`)));
@@ -4427,6 +4264,13 @@ function planAuthorizedModelProjection(args) {
4427
4264
  );
4428
4265
  plan.authorization = args.authorization;
4429
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
+ });
4430
4274
  return plan;
4431
4275
  }
4432
4276
  function planCatalogProjection(args, outputFields = { mode: "request" }) {
@@ -4489,151 +4333,790 @@ function planCatalogProjection(args, outputFields = { mode: "request" }) {
4489
4333
  if (virtual(path)) virtualLeaves.push(relative);
4490
4334
  else persisted.push(relative);
4491
4335
  }
4492
- const candidates = [];
4493
- const depProvenance = {};
4494
- const allVirtuals = [];
4495
- for (const relative of virtualLeaves) {
4496
- const segments = full(relative).split(".");
4497
- const name = segments.pop();
4498
- const registry = getScopeVirtualsObject(
4499
- snapshot.virtuals,
4500
- segments.flatMap((part) => [part, "sub"])
4501
- );
4502
- const descriptor = resolveSnapshotDescriptor(registry, name, virtualAccess);
4503
- if (!descriptor) continue;
4504
- allVirtuals.push(relative);
4505
- for (const dependency of descriptor.dependsOn) {
4506
- const localPrefix = relative.includes(".") ? relative.slice(0, relative.lastIndexOf(".") + 1) : "";
4507
- const dep = `${localPrefix}${dependency}`;
4508
- if (!depProvenance[dep]) depProvenance[dep] = [];
4509
- depProvenance[dep].push(relative);
4510
- }
4511
- if (!relative.includes("."))
4512
- candidates.push({
4513
- name,
4514
- descriptor,
4515
- dependsOn: [...descriptor.dependsOn],
4516
- populateDependencies: resolveVirtualPopulateDependencies(
4517
- snapshot,
4518
- args.scopePath ?? [],
4519
- name,
4520
- virtualAccess
4521
- ),
4522
- authState: states2[relative],
4523
- virtualAccess,
4524
- outputAccess
4525
- });
4336
+ const candidates = [];
4337
+ const depProvenance = {};
4338
+ const allVirtuals = [];
4339
+ for (const relative of virtualLeaves) {
4340
+ const segments = full(relative).split(".");
4341
+ const name = segments.pop();
4342
+ const registry = getScopeVirtualsObject(
4343
+ snapshot.virtuals,
4344
+ segments.flatMap((part) => [part, "sub"])
4345
+ );
4346
+ const descriptor = resolveSnapshotDescriptor(registry, name, virtualAccess);
4347
+ if (!descriptor) continue;
4348
+ allVirtuals.push(relative);
4349
+ for (const dependency of descriptor.dependsOn) {
4350
+ const localPrefix = relative.includes(".") ? relative.slice(0, relative.lastIndexOf(".") + 1) : "";
4351
+ const dep = `${localPrefix}${dependency}`;
4352
+ if (!depProvenance[dep]) depProvenance[dep] = [];
4353
+ depProvenance[dep].push(relative);
4354
+ }
4355
+ if (!relative.includes("."))
4356
+ candidates.push({
4357
+ name,
4358
+ descriptor,
4359
+ dependsOn: [...descriptor.dependsOn],
4360
+ populateDependencies: resolveVirtualPopulateDependencies(
4361
+ snapshot,
4362
+ args.scopePath ?? [],
4363
+ name,
4364
+ virtualAccess
4365
+ ),
4366
+ authState: states2[relative],
4367
+ virtualAccess,
4368
+ outputAccess
4369
+ });
4370
+ }
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;
4526
5092
  }
4527
- const ancestors = /* @__PURE__ */ new Set();
4528
- for (const path of [...persisted, ...allVirtuals]) {
4529
- const parts = path.split(".");
4530
- for (let i = 1; i < parts.length; i++) ancestors.add(parts.slice(0, i).join("."));
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);
4531
5101
  }
4532
- const children = {};
4533
- for (const name of [...ancestors].filter((p) => !p.includes("."))) {
4534
- const childIncludes = includes.filter((p) => p.startsWith(`${name}.`)).map((p) => p.slice(name.length + 1));
4535
- const childExcludes = excludes.filter((p) => p.startsWith(`${name}.`)).map((p) => `-${p.slice(name.length + 1)}`);
4536
- const childSelect = mode === "include" && !includes.includes(name) ? [...childIncludes, ...childExcludes] : childExcludes;
4537
- children[name] = planCatalogProjection(
4538
- {
4539
- ...args,
4540
- scopePath: [...args.scopePath ?? [], name, "sub"],
4541
- requestedSelect: childSelect,
4542
- effectiveSelect: childSelect,
4543
- related: [],
4544
- internalFetch: { baseFields: [] }
4545
- },
4546
- outputFields
4547
- );
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);
4548
5111
  }
4549
- const internal = args.internalFetch ?? {};
4550
- const fetchIdRetained = scope2.length === 0 || catalog.paths.includes(full("_id")) || !!catalog.dynamicPaths?.some((p) => p.endsWith("._id") && matchesCatalogPattern(p, full("_id")));
4551
- const identity = fetchIdRetained ? ["_id"] : [];
4552
- const always = scope2.length ? [] : [
4553
- .../* @__PURE__ */ new Set([
4554
- ...resolveAlwaysSelectForAccess(snapshot.alwaysSelectFields, outputAccess),
4555
- ...resolveAlwaysSelectForAccess(snapshot.alwaysSelectFields, docPermissionsAccess)
4556
- ])
4557
- ];
4558
- const joins = [...internal.joinFields ?? [], ...internal.extraPersistedFields ?? []];
4559
- const forced = [...always, ...joins, ...internal.baseFields ?? identity, ...internal.identityFields ?? []];
4560
- const fetchSafe = (path) => isSafeOutputPath(path) && !virtual(full(path));
4561
- const dependencies = Object.keys(depProvenance).filter(fetchSafe);
4562
- const childFetch = Object.entries(children).flatMap(([name, child]) => {
4563
- if (child.persistedFetchSelection.length) return child.persistedFetchSelection.map((p) => `${name}.${p}`);
4564
- depProvenance[name] = allVirtuals.filter((p) => p.startsWith(`${name}.`));
4565
- return [name];
4566
- });
4567
- const publicChildFetch = Object.entries(children).flatMap(
4568
- ([name, child]) => child.publicPersistedFetchSelection.length ? child.publicPersistedFetchSelection.map((path) => `${name}.${path}`) : [name]
4569
- );
4570
- const publicPersistedFetchSelection = compactPersistedProjection([
4571
- ...persisted,
4572
- ...dependencies,
4573
- ...forced.filter(fetchSafe),
4574
- ...identity,
4575
- ...publicChildFetch
4576
- ]);
4577
- const publicStructurePaths = Object.entries(children).flatMap(([name, child]) => {
4578
- if ([...persisted, ...dependencies, ...forced].some((path) => name === path || name.startsWith(`${path}.`)))
4579
- return [];
4580
- return child.publicPersistedFetchSelection.length ? (child.publicStructurePaths ?? []).map((path) => `${name}.${path}`) : [name];
4581
- });
4582
- const populateRefs = candidates.flatMap((candidate) => candidate.populateDependencies.map((dep) => dep.path));
4583
- const privateFields = [...dependencies, ...populateRefs, ...forced.filter(fetchSafe), ...identity, ...childFetch];
4584
- const fetch = compactPersistedProjection([...persisted, ...privateFields]);
4585
- const outputIdExcluded = excludes.includes("_id");
4586
- const coveredOutput = (path) => persisted.some((p) => p === path || path.startsWith(`${p}.`));
4587
- const outputPersisted = [.../* @__PURE__ */ new Set([...persisted.filter((p) => !p.includes(".")), ...Object.keys(children)])];
4588
- return {
4589
- receivingModelName,
4590
- scopePath: [...args.scopePath ?? []],
4591
- responseScopePath: Object.freeze(scope2),
4592
- virtualAccess,
4593
- outputAccess,
4594
- docPermissionsAccess,
4595
- selectionMode: mode,
4596
- effectiveSelectNorm: normalized,
4597
- outputPersistedFields: outputPersisted,
4598
- outputVirtualNames: candidates.map((c) => c.name),
4599
- outputSelection: [...outputPersisted, ...candidates.map((c) => c.name), ...outputIdExcluded ? ["-_id"] : []],
4600
- fieldStates: Object.freeze(states2),
4601
- minimalAncestorPaths: Object.freeze([...ancestors]),
4602
- persistedFetchSelection: fetch,
4603
- publicPersistedFetchSelection,
4604
- publicStructurePaths,
4605
- candidates,
4606
- depProvenance,
4607
- virtualOnlyDeps: Object.keys(depProvenance).filter((p) => fetchSafe(p) && !coveredOutput(p)),
4608
- internalOnlyFields: [
4609
- ...new Set(privateFields.filter((p) => !coveredOutput(p) && (p !== "_id" || outputIdExcluded)))
4610
- ],
4611
- outputIdExcluded,
4612
- fetchIdRetained,
4613
- internalIdentityFields: identity,
4614
- internalJoinFields: [...new Set(joins)],
4615
- childPlans: children,
4616
- // A parent never supplies its authority to a target; related execution will
4617
- // call planAuthorizedModelProjection with the independently derived owner.
4618
- relatedPlans: (args.related ?? []).map(
4619
- (rel) => planVirtualProjection({
4620
- ...rel,
4621
- receivingModelName: rel.targetModelName,
4622
- snapshot: rel.targetSnapshot,
4623
- globalPermissions
4624
- })
4625
- )
4626
- };
5112
+ return state;
4627
5113
  }
4628
- var init_output_projection = __esm({
4629
- "src/acl/output-projection.ts"() {
4630
- init_query();
4631
- init_authorization_snapshot();
4632
- init_field_catalog();
4633
- init_field_authorization();
4634
- init_virtual_populate_dependencies();
4635
- init_service_authorization();
4636
- 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();
4637
5120
  }
4638
5121
  });
4639
5122
 
@@ -4724,15 +5207,15 @@ import {
4724
5207
  isBoolean as isBoolean2,
4725
5208
  isEmpty as isEmpty2,
4726
5209
  isFunction as isFunction3,
4727
- isPlainObject as isPlainObject17,
5210
+ isPlainObject as isPlainObject18,
4728
5211
  isString as isString5
4729
5212
  } from "@web-ts-toolkit/utils";
4730
5213
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
4731
5214
  function isAndFilter(filter2) {
4732
- 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);
4733
5216
  }
4734
5217
  function isMergeableClause(filter2) {
4735
- return !!filter2 && isPlainObject17(filter2) && Object.keys(filter2).every((key) => !key.startsWith("$"));
5218
+ return !!filter2 && isPlainObject18(filter2) && Object.keys(filter2).every((key) => !key.startsWith("$"));
4736
5219
  }
4737
5220
  function optimizeAndFilter(clausesInput) {
4738
5221
  const clauses = [];
@@ -4753,7 +5236,7 @@ function optimizeAndFilter(clausesInput) {
4753
5236
  const entries = Array.from(value, dedupeKey);
4754
5237
  return entries.every((entry) => entry !== void 0) ? `array:${JSON.stringify(entries)}` : void 0;
4755
5238
  }
4756
- if (isPlainObject17(value)) {
5239
+ if (isPlainObject18(value)) {
4757
5240
  const entries = Object.keys(value).sort().map((key) => [key, dedupeKey(value[key])]);
4758
5241
  return entries.every(([, entry]) => entry !== void 0) ? `object:${JSON.stringify(entries)}` : void 0;
4759
5242
  }
@@ -4801,7 +5284,7 @@ function optimizeAndFilter(clausesInput) {
4801
5284
  }
4802
5285
  function normalizeFilter(filter2) {
4803
5286
  if (filter2 === false) return false;
4804
- if (!filter2 || !isPlainObject17(filter2) || isEmpty2(filter2)) return null;
5287
+ if (!filter2 || !isPlainObject18(filter2) || isEmpty2(filter2)) return null;
4805
5288
  if (!isAndFilter(filter2)) {
4806
5289
  return filter2;
4807
5290
  }
@@ -4879,7 +5362,7 @@ async function setRequestPermissions(req) {
4879
5362
  if (hasFieldValue && owner === void 0) return;
4880
5363
  const globalPermissions = getGlobalOption("globalPermissions");
4881
5364
  const permissions = isFunction3(globalPermissions) ? await globalPermissions.call(req, req) : void 0;
4882
- if (isPlainObject17(permissions)) req[requestPermissionField] = permissions;
5365
+ if (isPlainObject18(permissions)) req[requestPermissionField] = permissions;
4883
5366
  else if (isArray8(permissions)) req[requestPermissionField] = arrayToRecord(permissions);
4884
5367
  else if (isString5(permissions)) req[requestPermissionField] = { [permissions]: true };
4885
5368
  else req[requestPermissionField] = {};
@@ -5278,7 +5761,7 @@ var init_filter_resolution = __esm({
5278
5761
  // src/acl/virtual-populate-execution.ts
5279
5762
  import { Document as Document4, mongo as mongo4 } from "mongoose";
5280
5763
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "util";
5281
- import { isPlainObject as isPlainObject20 } from "@web-ts-toolkit/utils";
5764
+ import { isPlainObject as isPlainObject21 } from "@web-ts-toolkit/utils";
5282
5765
  function projectVirtualPopulateView(source, selection, structurePaths = []) {
5283
5766
  const root = { children: /* @__PURE__ */ new Map() };
5284
5767
  for (const path of compactPersistedProjection(selection)) {
@@ -5310,8 +5793,8 @@ function equivalentVirtualPopulatePredicate(left, right) {
5310
5793
  }
5311
5794
  if (Array.isArray(left) || Array.isArray(right))
5312
5795
  return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((entry, index) => equivalentVirtualPopulatePredicate(entry, right[index]));
5313
- if (isPlainObject20(left) || isPlainObject20(right)) {
5314
- if (!isPlainObject20(left) || !isPlainObject20(right)) return false;
5796
+ if (isPlainObject21(left) || isPlainObject21(right)) {
5797
+ if (!isPlainObject21(left) || !isPlainObject21(right)) return false;
5315
5798
  const a = Object.keys(left), b = Object.keys(right);
5316
5799
  return a.length === b.length && a.every(
5317
5800
  (key, index) => key === b[index] && equivalentVirtualPopulatePredicate(
@@ -5714,7 +6197,7 @@ var init_virtual_populate_execution = __esm({
5714
6197
  publicViewIdentities = /* @__PURE__ */ new WeakMap();
5715
6198
  familyRawFetches = /* @__PURE__ */ new WeakMap();
5716
6199
  addressKey = (address) => JSON.stringify(address);
5717
- 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;
5718
6201
  originalRef = (source, key) => {
5719
6202
  const record3 = storage(source);
5720
6203
  return {
@@ -5741,21 +6224,50 @@ var init_virtual_populate_execution = __esm({
5741
6224
  });
5742
6225
 
5743
6226
  // src/acl/output-field-filter.ts
5744
- import { isPlainObject as isPlainObject21 } from "@web-ts-toolkit/utils";
6227
+ import { types as types5 } from "util";
6228
+ import { isPlainObject as isPlainObject22 } from "@web-ts-toolkit/utils";
6229
+ function assertOwningOutputDocuments(handle) {
6230
+ const owner = readOutputDocumentOwner(handle);
6231
+ if (owner) {
6232
+ readDocumentAuthorizationAccess(owner.handle, owner.binding);
6233
+ assertOwningOutputDocuments(owner.handle);
6234
+ }
6235
+ }
6236
+ function prepareOutputDocumentAuthorization(authorization, binding, configuration) {
6237
+ const access = readServiceAuthorizationAccess(authorization, binding);
6238
+ const key = `docPermissions.${access.docPermissionsAccess}`;
6239
+ const docPermissions = configuration.docPermissions;
6240
+ const invariant = /^[A-Za-z0-9_-]+$/.test(access.docPermissionsAccess) && (docPermissions == null || isPlainObject22(docPermissions));
6241
+ const option = invariant ? getCapturedAuthorizationOption(configuration, key) : void 0;
6242
+ const hook = typeof option === "function" ? option : void 0;
6243
+ const resolveHook = invariant ? () => hook : () => {
6244
+ const slice = { catalog: configuration.catalog, ...copyAuthorizationValue({ docPermissions }, true) };
6245
+ const option2 = getCapturedAuthorizationOption(slice, key);
6246
+ return typeof option2 === "function" ? option2 : void 0;
6247
+ };
6248
+ return async (args) => {
6249
+ if (args.authorization !== authorization) authorizationError("document resolver call mismatch");
6250
+ assertAuthorizationBinding(authorization, args.binding);
6251
+ return resolveOutputDocumentAuthorizationWithHook(args, access, resolveHook);
6252
+ };
6253
+ }
5745
6254
  async function resolveOutputDocumentAuthorization(args) {
6255
+ const configuration = readServiceDocumentPermissions(args.authorization, args.binding);
6256
+ return prepareOutputDocumentAuthorization(args.authorization, args.binding, configuration)(args);
6257
+ }
6258
+ async function resolveOutputDocumentAuthorizationWithHook(args, access, resolveHook) {
5746
6259
  const { authorization, binding } = args;
5747
- const { configuration, access } = readServiceAuthorization(authorization, binding);
5748
6260
  const stage = args.stage ?? createDocumentAuthorizationStage(authorization, binding, args.snapshot);
5749
6261
  if (args.stage) assertDocumentAuthorizationStage(stage, authorization, binding, args.snapshot);
5750
6262
  const handle = await resolveDocumentAuthorization(stage, async function(doc, permissions) {
5751
6263
  if (args.owningDocument) return readDocumentAuthorization(args.owningDocument, args.owningBinding).grants;
5752
6264
  if (args.knownOutput) return {};
5753
- const hook = getCapturedAuthorizationOption(configuration, `docPermissions.${access.docPermissionsAccess}`);
5754
- if (typeof hook !== "function") return {};
6265
+ const hook = resolveHook();
6266
+ if (!hook) return {};
5755
6267
  try {
5756
6268
  const run = () => hook.call(this, doc, permissions, args.context);
5757
6269
  const grants = await getRequestWorkState(binding.request, binding.runtime).hookGate.run(run);
5758
- return isPlainObject21(grants) ? grants : {};
6270
+ return isPlainObject22(grants) ? grants : {};
5759
6271
  } catch (error2) {
5760
6272
  warn("docPermissions hook failed; applying empty document permissions", {
5761
6273
  modelName: binding.modelName,
@@ -5766,13 +6278,12 @@ async function resolveOutputDocumentAuthorization(args) {
5766
6278
  return {};
5767
6279
  }
5768
6280
  });
5769
- if (args.knownOutput || args.owningDocument && unresolvedDocuments.has(args.owningDocument))
5770
- unresolvedDocuments.add(handle);
5771
- if (args.owningDocument) owningDocuments.set(handle, { handle: args.owningDocument, binding: args.owningBinding });
6281
+ bindOutputDocumentOwner(handle, args.knownOutput, args.owningDocument, args.owningBinding);
5772
6282
  return handle;
5773
6283
  }
5774
6284
  function evaluateRequestRule(handle, binding, entry, prefix, access) {
5775
- const owner = owningDocuments.get(handle);
6285
+ assertOwningOutputDocuments(handle);
6286
+ const owner = readOutputDocumentOwner(handle);
5776
6287
  if (owner && !entry.path.startsWith(`${(binding.scopePath ?? []).join(".")}.`)) {
5777
6288
  return evaluateRequestRule(owner.handle, owner.binding, entry, prefix, access);
5778
6289
  }
@@ -5780,65 +6291,84 @@ function evaluateRequestRule(handle, binding, entry, prefix, access) {
5780
6291
  handle,
5781
6292
  binding,
5782
6293
  `request:${access}:${entry.path}`,
5783
- function(permissions, grants) {
5784
- return evaluateScopedAccessRule({
5785
- req: this,
5786
- rule: entry.rule,
5787
- globalPermissions: permissions,
5788
- docPermissions: grants,
5789
- modelPermissionPrefix: prefix
5790
- });
6294
+ async function(permissions, grants) {
6295
+ const { authorization } = readDocumentAuthorizationAccess(handle, binding);
6296
+ const classification = requestRuleClassification(entry, authorization, permissions, prefix);
6297
+ let allowed = classification?.decision;
6298
+ if (allowed === void 0) {
6299
+ allowed = await evaluateScopedAccessRule({
6300
+ req: this,
6301
+ rule: entry.rule,
6302
+ globalPermissions: permissions,
6303
+ docPermissions: grants,
6304
+ modelPermissionPrefix: prefix
6305
+ });
6306
+ }
6307
+ assertOwningOutputDocuments(handle);
6308
+ return allowed;
5791
6309
  }
5792
6310
  );
5793
6311
  }
5794
6312
  function evaluateAuthorizedOutputField(handle, binding, field) {
5795
- const { authorization } = readDocumentAuthorization(handle, binding);
5796
- const { configuration, authorization: policy, access } = readServiceAuthorization(authorization, binding);
6313
+ const { authorization } = readDocumentAuthorizationAccess(handle, binding);
6314
+ assertOwningOutputDocuments(handle);
5797
6315
  const path = [...binding.scopePath ?? [], field].join(".");
5798
- const entries = extractOutputFieldRuleEntries(
5799
- configuration.permissionSchema,
5800
- path,
5801
- access.outputAccess
5802
- );
5803
- return memoizeDocumentFieldDecision(handle, binding, `output:${path}`, function(permissions, grants) {
5804
- const args = {
6316
+ const decision = memoizeDocumentFieldDecision(handle, binding, `output:${path}`, async function(permissions) {
6317
+ const policy = callFieldPolicy(authorization, binding);
6318
+ const { outputAccess } = readDocumentAuthorizationAccess(handle, binding);
6319
+ const prepared = prepareOutputPath(policy, authorization, binding, path, outputAccess);
6320
+ const unresolved = isUnresolvedOutputDocument(handle);
6321
+ const state = unresolved ? prepared.state ?? classifyEffectiveFieldAuthorization({
5805
6322
  path,
5806
- rules: entries.map((entry) => entry.rule),
6323
+ rules: prepared.entries.map((entry) => entry.rule),
6324
+ modelPermissionPrefix: policy.prefix,
5807
6325
  outputFields: policy.outputFields,
5808
- globalPermissions: permissions,
5809
- modelPermissionPrefix: configuration.modelPermissionPrefix ?? ""
5810
- };
5811
- if (unresolvedDocuments.has(handle) && classifyEffectiveFieldAuthorization(args) !== "granted") return false;
5812
- return evaluateEffectiveFieldAuthorization({
5813
- ...args,
5814
- req: this,
5815
- docPermissions: grants,
5816
- evaluateRule: (_rule, index) => evaluateRequestRule(handle, binding, entries[index], args.modelPermissionPrefix, access.outputAccess)
5817
- });
6326
+ globalPermissions: permissions
6327
+ }) : void 0;
6328
+ let allowed;
6329
+ if (unresolved && state !== "granted") allowed = false;
6330
+ else if (prepared.backendGrant) allowed = true;
6331
+ else {
6332
+ allowed = true;
6333
+ for (const entry of prepared.entries) {
6334
+ if (!await evaluateRequestRule(handle, binding, entry, policy.prefix, outputAccess)) {
6335
+ allowed = false;
6336
+ break;
6337
+ }
6338
+ }
6339
+ }
6340
+ assertOwningOutputDocuments(handle);
6341
+ return allowed;
5818
6342
  });
6343
+ return readOutputDocumentOwner(handle) ? decision.then((allowed) => {
6344
+ assertOwningOutputDocuments(handle);
6345
+ return allowed;
6346
+ }) : decision;
5819
6347
  }
5820
6348
  async function requestOutputFieldPaths(handle, binding, access) {
5821
- const { authorization } = readDocumentAuthorization(handle, binding);
5822
- const { configuration } = readServiceAuthorization(authorization, binding);
5823
- const schema = configuration.permissionSchema;
6349
+ const staticFields = tryStaticRequestFieldPaths(handle, binding, access);
6350
+ if (staticFields) {
6351
+ await Promise.resolve();
6352
+ readDocumentAuthorizationAccess(handle, binding);
6353
+ return staticFields;
6354
+ }
6355
+ const { authorization } = readDocumentAuthorizationAccess(handle, binding);
6356
+ assertOwningOutputDocuments(handle);
6357
+ const policy = callFieldPolicy(authorization, binding);
5824
6358
  const fields = [];
5825
- for (const path of Object.keys(schema ?? {})) {
5826
- const entries = extractOutputFieldRuleEntries(schema, path, access);
6359
+ for (const path of policy.requestPaths ?? Object.keys(policy.schema ?? {})) {
6360
+ const { entries } = prepareOutputPath(policy, authorization, binding, path, access);
5827
6361
  let allowed = true;
5828
6362
  for (const entry of entries) {
5829
- if (!await evaluateRequestRule(
5830
- handle,
5831
- binding,
5832
- entry,
5833
- configuration.modelPermissionPrefix ?? "",
5834
- access
5835
- )) {
6363
+ if (!await evaluateRequestRule(handle, binding, entry, policy.prefix, access)) {
5836
6364
  allowed = false;
5837
6365
  break;
5838
6366
  }
5839
6367
  }
5840
6368
  if (allowed && entries.length) fields.push(path);
5841
6369
  }
6370
+ assertOwningOutputDocuments(handle);
6371
+ readDocumentAuthorizationAccess(handle, binding);
5842
6372
  return fields;
5843
6373
  }
5844
6374
  function authorizeEmbeddedOutputPlan(parent, child) {
@@ -5859,24 +6389,24 @@ function authorizeEmbeddedOutputPlan(parent, child) {
5859
6389
  function hasWholeOutputValueGrant(plan, field) {
5860
6390
  if (plan.fieldStates?.[field] !== "granted") return false;
5861
6391
  const binding = plan.authorizationBinding;
5862
- const { authorization } = readServiceAuthorization(plan.authorization, binding);
5863
- return hasExplicitFieldGrant(authorization.outputFields, [...binding.scopePath ?? [], field].join("."));
6392
+ const { outputFields } = readServiceOutputPolicy(plan.authorization, binding);
6393
+ return hasExplicitFieldGrant(outputFields, [...binding.scopePath ?? [], field].join("."));
5864
6394
  }
5865
6395
  function copyOutputValue(value, plan, path) {
5866
- const { configuration } = readServiceAuthorization(plan.authorization, plan.authorizationBinding);
5867
- const virtualValue = configuration.catalog.virtualPaths?.some((p) => matchesCatalogPattern(p, path));
5868
- const opaque = configuration.catalog.opaquePaths?.some((p) => matchesCatalogPattern(p, path));
6396
+ const { catalog } = readServiceOutputPolicy(plan.authorization, plan.authorizationBinding);
6397
+ const virtualValue = catalog.virtualPaths?.some((p) => matchesCatalogPattern(p, path));
6398
+ const opaque = catalog.opaquePaths?.some((p) => matchesCatalogPattern(p, path));
5869
6399
  const excluded = plan.effectiveSelectNorm.filter((token) => token.startsWith("-")).map((token) => [...plan.authorizationBinding.scopePath ?? [], token.slice(1)].join("."));
5870
6400
  const visit = (input, current) => {
5871
6401
  if (Array.isArray(input)) return input.map((entry) => visit(entry, current));
5872
6402
  if (input instanceof Map) return visit(Object.fromEntries(input), current);
5873
- if (!isPlainObject21(input)) return deepIsolateValue(input);
6403
+ if (!isPlainObject22(input)) return deepIsolateValue(input);
5874
6404
  const output = {};
5875
6405
  for (const [key, entry] of Object.entries(input)) {
5876
6406
  const child = `${current}.${key}`;
5877
6407
  if (excluded.some((entry2) => child === entry2 || child.startsWith(`${entry2}.`))) continue;
5878
6408
  const safeValueKey = !["__proto__", "constructor", "prototype", "_doc", "$__", "__v"].includes(key);
5879
- if (!(opaque ? safeValueKey : isSafeOutputPath(key)) || configuration.catalog.protectedPaths?.some((p) => matchesCatalogPattern(p, child, true)) || !opaque && !virtualValue && !isCatalogOutputPath(configuration.catalog, child))
6409
+ if (!(opaque ? safeValueKey : isSafeOutputPath(key)) || catalog.protectedPaths?.some((p) => matchesCatalogPattern(p, child, true)) || !opaque && !virtualValue && !isCatalogOutputPath(catalog, child))
5880
6410
  continue;
5881
6411
  output[key] = visit(entry, child);
5882
6412
  }
@@ -5886,7 +6416,7 @@ function copyOutputValue(value, plan, path) {
5886
6416
  }
5887
6417
  function copyAuthorizedReference(value, plan, path) {
5888
6418
  if (Array.isArray(value)) return value.map((entry) => copyAuthorizedReference(entry, plan, path));
5889
- if (!isPlainObject21(value)) return deepIsolateValue(value);
6419
+ if (!isPlainObject22(value)) return deepIsolateValue(value);
5890
6420
  const handle = getAssociatedDocumentAuthorization(value, plan.authorization);
5891
6421
  if (handle) {
5892
6422
  const copy = deepIsolateValue(value);
@@ -5899,8 +6429,8 @@ function retainOutputMetadata(output, source, configuration, scope2) {
5899
6429
  if (scope2.length || configuration.stripPermissionsField) return;
5900
6430
  const parts = (configuration.documentPermissionField ?? "_permissions").split(".");
5901
6431
  let value = source;
5902
- for (const part of parts) value = isPlainObject21(value) ? value[part] : void 0;
5903
- if (!isPlainObject21(value)) return;
6432
+ for (const part of parts) value = isPlainObject22(value) ? value[part] : void 0;
6433
+ if (!isPlainObject22(value)) return;
5904
6434
  const keys2 = configuration.exposedDocPermissionKeys;
5905
6435
  const metadata = Object.fromEntries(
5906
6436
  Object.entries(value).filter(
@@ -5910,7 +6440,7 @@ function retainOutputMetadata(output, source, configuration, scope2) {
5910
6440
  const copy = { ...output };
5911
6441
  let target = copy;
5912
6442
  for (const part of parts.slice(0, -1)) {
5913
- target[part] = isPlainObject21(target[part]) ? { ...target[part] } : {};
6443
+ target[part] = isPlainObject22(target[part]) ? { ...target[part] } : {};
5914
6444
  target = target[part];
5915
6445
  }
5916
6446
  target[parts[parts.length - 1]] = deepIsolateValue(metadata);
@@ -5919,27 +6449,37 @@ function retainOutputMetadata(output, source, configuration, scope2) {
5919
6449
  attachPermissionsAlias(output, parts.join("."));
5920
6450
  }
5921
6451
  function helperPlan(authorization, binding) {
5922
- const { configuration, authorization: policy, access } = readServiceAuthorization(authorization, binding);
5923
- if (binding.scopePath?.length && !isCatalogOutputPath(configuration.catalog, binding.scopePath.join(".")))
5924
- authorizationError("unknown output scope");
5925
- const plan = planCatalogProjection(
5926
- {
5927
- receivingModelName: binding.modelName,
5928
- snapshot: configuration,
5929
- ...access,
5930
- effectiveSelect: [],
5931
- scopePath: (binding.scopePath ?? []).flatMap((part) => [part, "sub"]),
5932
- globalPermissions: getAuthorizationPermissions(authorization, binding)
5933
- },
5934
- policy.outputFields
5935
- );
5936
- 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;
5937
6469
  }
5938
6470
  async function filterExistingOutput(source, plan, handle, associated) {
5939
6471
  const binding = plan.authorizationBinding;
5940
6472
  const { configuration } = readServiceAuthorization(plan.authorization, binding);
5941
6473
  const output = {};
5942
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
+ }
5943
6483
  for (const field of /* @__PURE__ */ new Set([...plan.outputPersistedFields, ...plan.outputVirtualNames])) {
5944
6484
  if (!Object.prototype.hasOwnProperty.call(source, field) || source[field] === void 0) continue;
5945
6485
  const childPlan = plan.childPlans[field];
@@ -5952,11 +6492,11 @@ async function filterExistingOutput(source, plan, handle, associated) {
5952
6492
  for (const entry of value2) values.push(await one(entry) ?? null);
5953
6493
  return values;
5954
6494
  }
5955
- if (!isPlainObject21(value2)) return value2 === null ? null : void 0;
6495
+ if (!isPlainObject22(value2)) return value2 === null ? null : void 0;
5956
6496
  const childHandle = associated ? getAssociatedDocumentAuthorization(value2) : void 0;
5957
6497
  let child = scoped;
5958
6498
  if (childHandle) {
5959
- const state = readDocumentAuthorization(childHandle, scoped.authorizationBinding);
6499
+ const state = readDocumentAuthorizationAccess(childHandle, scoped.authorizationBinding);
5960
6500
  if (getAuthorizationProvenance(state.authorization) !== getAuthorizationProvenance(plan.authorization))
5961
6501
  authorizationError("child call mismatch");
5962
6502
  child = helperPlan(state.authorization, scoped.authorizationBinding);
@@ -5980,7 +6520,7 @@ async function filterExistingOutput(source, plan, handle, associated) {
5980
6520
  const value = await one(source[field]);
5981
6521
  if (value !== void 0) output[field] = value;
5982
6522
  fields.push(...childFields);
5983
- } else if (await evaluateAuthorizedOutputField(handle, binding, field)) {
6523
+ } else if (staticDecisions ? staticDecisions.get(field) === true : await evaluateAuthorizedOutputField(handle, binding, field)) {
5984
6524
  const path = [...binding.scopePath ?? [], field].join(".");
5985
6525
  output[field] = configuration.catalog.referencePaths?.some((p) => matchesCatalogPattern(p, path)) ? copyAuthorizedReference(source[field], plan, path) : copyOutputValue(source[field], plan, path);
5986
6526
  if (associated) transferDocumentAuthorizationGraph(source[field], output[field]);
@@ -6020,7 +6560,7 @@ async function filterModelOutputForHelper(args) {
6020
6560
  if (normalized.kind === "document") {
6021
6561
  const { documentAuthorization: handle2, binding: binding2 } = normalized;
6022
6562
  assertDocumentAuthorization(handle2, { binding: binding2, output: args.doc, outputAccess: access });
6023
- const state = readDocumentAuthorization(handle2, binding2);
6563
+ const state = readDocumentAuthorizationAccess(handle2, binding2);
6024
6564
  return filterExistingOutput(
6025
6565
  args.doc,
6026
6566
  helperPlan(state.authorization, binding2),
@@ -6032,7 +6572,7 @@ async function filterModelOutputForHelper(args) {
6032
6572
  const plan = helperPlan(normalized.authorization, binding);
6033
6573
  if (args.doc == null) return { output: args.doc, fields: [] };
6034
6574
  const source = isolateDocForOutput(args.doc);
6035
- 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");
6036
6576
  const knownOutput = !!args.doc && typeof args.doc === "object" && isKnownAuthorizationOutput(args.doc);
6037
6577
  const handle = await resolveOutputDocumentAuthorization({
6038
6578
  authorization: normalized.authorization,
@@ -6043,7 +6583,6 @@ async function filterModelOutputForHelper(args) {
6043
6583
  });
6044
6584
  return filterExistingOutput(source, plan, handle, false);
6045
6585
  }
6046
- var unresolvedDocuments, owningDocuments;
6047
6586
  var init_output_field_filter = __esm({
6048
6587
  "src/acl/output-field-filter.ts"() {
6049
6588
  init_permissions_alias();
@@ -6057,8 +6596,7 @@ var init_output_field_filter = __esm({
6057
6596
  init_field_authorization();
6058
6597
  init_field_catalog();
6059
6598
  init_output_projection();
6060
- unresolvedDocuments = /* @__PURE__ */ new WeakSet();
6061
- owningDocuments = /* @__PURE__ */ new WeakMap();
6599
+ init_output_field_policy();
6062
6600
  }
6063
6601
  });
6064
6602
 
@@ -6127,28 +6665,54 @@ __export(finalize_model_output_exports, {
6127
6665
  finalizeModelOutput: () => finalizeModelOutput,
6128
6666
  finalizeModelOutputs: () => finalizeModelOutputs
6129
6667
  });
6130
- import { get as get9, isPlainObject as isPlainObject22, set as set7 } from "@web-ts-toolkit/utils";
6131
- async function finalizeSingleDoc(args, input) {
6132
- const scopePath = args.scopePath;
6668
+ import { get as get9, isPlainObject as isPlainObject23, set as set7 } from "@web-ts-toolkit/utils";
6669
+ function assertFinalizerCall(args, prepared) {
6133
6670
  const plan = args.plan;
6134
6671
  const binding = plan.authorizationBinding;
6135
- const captured = plan.authorization && binding ? readServiceAuthorization(plan.authorization, binding) : void 0;
6136
- if (plan.authorization && (!binding || binding.request !== args.request || binding.modelName !== args.receivingModelName || captured?.access.virtualAccess !== args.virtualAccess || captured.access.outputAccess !== args.outputAccess || captured.access.docPermissionsAccess !== args.docPermissionsAccess || (binding.scopePath ?? []).join(".") !== scopePath.filter((p) => p !== "sub").join("."))) {
6672
+ if (plan.authorization !== prepared.authorization) authorizationError("finalizer call changed during pass");
6673
+ if (plan.authorization && binding) assertAuthorizationBinding(plan.authorization, binding);
6674
+ const access = prepared.policy?.access;
6675
+ if (plan.authorization && (!binding || binding.request !== args.request || binding.modelName !== args.receivingModelName || access?.virtualAccess !== args.virtualAccess || access.outputAccess !== args.outputAccess || access.docPermissionsAccess !== args.docPermissionsAccess || (binding.scopePath ?? []).join(".") !== args.scopePath.filter((p) => p !== "sub").join("."))) {
6137
6676
  authorizationError("finalizer call/model/scope/access mismatch");
6138
6677
  }
6139
- const snapshot = captured ? captured.configuration : args.snapshot;
6678
+ }
6679
+ function prepareFinalizer(args, sharedContext = false) {
6680
+ const { authorization, authorizationBinding: binding } = args.plan;
6681
+ const policy = authorization && binding ? readServiceOutputPolicy(authorization, binding) : void 0;
6682
+ assertFinalizerCall(args, { authorization, policy });
6683
+ const configuration = authorization ? readServiceFinalizerConfiguration(authorization, binding) : void 0;
6684
+ const snapshot = configuration ? configuration : deepIsolateValue(args.snapshot);
6685
+ return {
6686
+ authorization,
6687
+ policy,
6688
+ snapshot,
6689
+ baseContext: deepIsolateValue(args.context ?? {}),
6690
+ sharedContext,
6691
+ scopeVirtualNames: getScopeVirtualNames(snapshot, args.scopePath),
6692
+ scopedSchema: configuration ? null : getScopedPermissionSchema2(snapshot.permissionSchema, args.scopePath),
6693
+ permissions: authorization ? getAuthorizationPermissions(authorization, binding) : void 0,
6694
+ resolveDocument: authorization ? prepareOutputDocumentAuthorization(authorization, binding, configuration) : void 0
6695
+ };
6696
+ }
6697
+ async function finalizeSingleDoc(args, input, prepared) {
6698
+ assertFinalizerCall(args, prepared);
6699
+ const scopePath = args.scopePath;
6700
+ const plan = args.plan;
6701
+ const binding = plan.authorizationBinding;
6702
+ const captured = prepared.policy;
6703
+ const snapshot = prepared.snapshot;
6140
6704
  const limit = args.resolvedLimit;
6141
6705
  const gate = args.sharedGate;
6142
6706
  const original = getIncludeOriginal(input);
6143
6707
  const privateRow = args.virtualPopulateRow ?? (original && typeof original === "object" ? getVirtualPopulateRow(original) : void 0);
6144
6708
  const privateAddress = args.virtualPopulateAddress ?? [];
6145
6709
  const isolated = isolateDocForOutput(input);
6146
- const output = isPlainObject22(isolated) ? isolated : {};
6147
- if (captured && isPlainObject22(input))
6710
+ const output = isPlainObject23(isolated) ? isolated : {};
6711
+ if (captured && isPlainObject23(input))
6148
6712
  for (const key of Object.keys(output)) {
6149
6713
  transferDocumentAuthorizationGraph(input[key], output[key]);
6150
6714
  }
6151
- const baseContext = args.context ?? {};
6715
+ const baseContext = prepared.sharedContext ? deepIsolateValue(prepared.baseContext) : prepared.baseContext;
6152
6716
  const operation = captured?.access.operation ?? baseContext.operation ?? args.operation ?? args.virtualAccess;
6153
6717
  const scopeContext = {
6154
6718
  ...baseContext,
@@ -6166,7 +6730,7 @@ async function finalizeSingleDoc(args, input) {
6166
6730
  if (captured) {
6167
6731
  const projected = args.documentAuthorizationStage ? input : deepIsolateValue(output);
6168
6732
  metadataSource = deepIsolateValue(output);
6169
- documentAuthorization = await resolveOutputDocumentAuthorization({
6733
+ documentAuthorization = await prepared.resolveDocument({
6170
6734
  authorization: plan.authorization,
6171
6735
  binding,
6172
6736
  snapshot: projected,
@@ -6179,13 +6743,10 @@ async function finalizeSingleDoc(args, input) {
6179
6743
  }
6180
6744
  const docGrants = documentAuthorization ? readDocumentAuthorization(documentAuthorization, binding).grants : await resolveDocPermissions(args, output, scopeContext);
6181
6745
  scopeContext.docPermissions = deepIsolateValue(docGrants);
6182
- const globalPerms = captured ? getAuthorizationPermissions(plan.authorization, binding) : resolveGlobalPermissions(args);
6183
- const modelPermissionPrefix = snapshot.modelPermissionPrefix ?? "";
6184
- const documentPermissionField = snapshot.documentPermissionField ?? "_permissions";
6185
- const scopedSchema = getScopedPermissionSchema2(
6186
- snapshot.permissionSchema ?? null,
6187
- scopePath
6188
- );
6746
+ const globalPerms = prepared.permissions ?? resolveGlobalPermissions(args);
6747
+ const modelPermissionPrefix = captured ? "" : deepIsolateValue(snapshot.modelPermissionPrefix ?? "");
6748
+ const documentPermissionField = captured ? "_permissions" : deepIsolateValue(snapshot.documentPermissionField ?? "_permissions");
6749
+ const scopedSchema = deepIsolateValue(prepared.scopedSchema);
6189
6750
  const childPlans = plan.childPlans ?? {};
6190
6751
  for (const [containerName, childPlan] of Object.entries(childPlans)) {
6191
6752
  if (!(containerName in output)) continue;
@@ -6199,17 +6760,18 @@ async function finalizeSingleDoc(args, input) {
6199
6760
  );
6200
6761
  continue;
6201
6762
  }
6202
- if (captured && !isPlainObject22(rawContainer) && !Array.isArray(rawContainer)) {
6763
+ if (captured && !isPlainObject23(rawContainer) && !Array.isArray(rawContainer)) {
6203
6764
  delete output[containerName];
6204
6765
  continue;
6205
6766
  }
6206
6767
  retainRawAssociation(output, containerName, rawContainer);
6207
- const childSnapshot = snapshot;
6208
6768
  const childBase = {
6209
6769
  ...args,
6210
6770
  scopePath: [...childPlan.scopePath ?? [...scopePath, containerName, "sub"]],
6211
6771
  plan: captured ? authorizeEmbeddedOutputPlan(plan, childPlan) : childPlan,
6212
- snapshot: childSnapshot,
6772
+ // Authenticated preparation reads its own authority. Do not clone an
6773
+ // otherwise unused public configuration graph on default traversal.
6774
+ snapshot: args.snapshot,
6213
6775
  // Embedded reuses the owning parent's grants + accesses (VIRT-00A D2).
6214
6776
  docPermissions: docGrants,
6215
6777
  context: scopeContext,
@@ -6220,10 +6782,11 @@ async function finalizeSingleDoc(args, input) {
6220
6782
  related: [],
6221
6783
  virtualPopulateRow: privateRow
6222
6784
  };
6785
+ let childPreparation;
6223
6786
  const finalizeOneChild = async (rawChild, address) => {
6224
6787
  if (captured && Array.isArray(rawChild))
6225
6788
  return mapWithConcurrencyLimit(rawChild, limit, (entry, index) => finalizeOneChild(entry, [...address, index]));
6226
- if (!isPlainObject22(rawChild) && !Array.isArray(rawChild)) return captured ? null : deepIsolateValue(rawChild);
6789
+ if (!isPlainObject23(rawChild) && !Array.isArray(rawChild)) return captured ? null : deepIsolateValue(rawChild);
6227
6790
  if (args.traversal?.finalizeEmbeddedChildren) {
6228
6791
  return args.traversal.finalizeEmbeddedChildren({
6229
6792
  containerName,
@@ -6240,7 +6803,14 @@ async function finalizeSingleDoc(args, input) {
6240
6803
  } : { ...args, virtualPopulateRow: privateRow, virtualPopulateAddress: address }
6241
6804
  });
6242
6805
  }
6243
- return finalizeSingleDoc({ ...childBase, virtualPopulateAddress: address }, rawChild);
6806
+ return finalizeSingleDoc(
6807
+ { ...childBase, virtualPopulateAddress: address },
6808
+ rawChild,
6809
+ childPreparation ??= prepareFinalizer(
6810
+ childBase,
6811
+ Array.isArray(rawContainer) && (rawContainer.length > 1 || Array.isArray(rawContainer[0]))
6812
+ )
6813
+ );
6244
6814
  };
6245
6815
  if (Array.isArray(rawContainer)) {
6246
6816
  const finalized = await mapWithConcurrencyLimit(
@@ -6249,7 +6819,7 @@ async function finalizeSingleDoc(args, input) {
6249
6819
  (entry, index) => finalizeOneChild(entry, [...privateAddress, containerName, index])
6250
6820
  );
6251
6821
  output[containerName] = finalized;
6252
- } else if (isPlainObject22(rawContainer)) {
6822
+ } else if (isPlainObject23(rawContainer)) {
6253
6823
  output[containerName] = await finalizeOneChild(rawContainer, [
6254
6824
  ...privateAddress,
6255
6825
  containerName
@@ -6292,8 +6862,9 @@ async function finalizeSingleDoc(args, input) {
6292
6862
  context: scopeContext,
6293
6863
  related: target.plan.relatedPlans?.length ? (args.related ?? []).filter((entry) => entry.path.startsWith(`${target.path}.`)) : []
6294
6864
  };
6865
+ let relatedPreparation;
6295
6866
  const finalizeOneRelated = async (rawChild, originalChild = rawChild) => {
6296
- if (!isPlainObject22(rawChild) && !Array.isArray(rawChild)) return rawChild;
6867
+ if (!isPlainObject23(rawChild) && !Array.isArray(rawChild)) return rawChild;
6297
6868
  if (typeof rawChild?._bsontype === "string") return rawChild;
6298
6869
  const childOriginal = getIncludeOriginal(originalChild);
6299
6870
  const childRow = childOriginal && typeof childOriginal === "object" ? getVirtualPopulateRow(childOriginal) : void 0;
@@ -6305,7 +6876,11 @@ async function finalizeSingleDoc(args, input) {
6305
6876
  parentArgs: { ...args, virtualPopulateRow: childRow, virtualPopulateAddress: [] }
6306
6877
  });
6307
6878
  }
6308
- return finalizeSingleDoc({ ...relatedBase, virtualPopulateRow: childRow }, rawChild);
6879
+ return finalizeSingleDoc(
6880
+ { ...relatedBase, virtualPopulateRow: childRow },
6881
+ rawChild,
6882
+ relatedPreparation ??= prepareFinalizer(relatedBase, Array.isArray(rawRelated) && rawRelated.length > 1)
6883
+ );
6309
6884
  };
6310
6885
  let finalized;
6311
6886
  if (Array.isArray(rawRelated)) {
@@ -6314,7 +6889,7 @@ async function finalizeSingleDoc(args, input) {
6314
6889
  limit,
6315
6890
  (entry, index) => finalizeOneRelated(entry, Array.isArray(originalRelated) ? originalRelated[index] : void 0)
6316
6891
  );
6317
- } else if (isPlainObject22(rawRelated)) {
6892
+ } else if (isPlainObject23(rawRelated)) {
6318
6893
  finalized = await finalizeOneRelated(rawRelated, originalRelated);
6319
6894
  } else {
6320
6895
  continue;
@@ -6325,18 +6900,24 @@ async function finalizeSingleDoc(args, input) {
6325
6900
  } catch {
6326
6901
  }
6327
6902
  }
6328
- const scopeVirtualNames = getScopeVirtualNames(snapshot, scopePath);
6329
- for (const virtualName of scopeVirtualNames) {
6903
+ for (const virtualName of prepared.scopeVirtualNames) {
6330
6904
  if (virtualName in output) delete output[virtualName];
6331
6905
  }
6332
- const stableBase = deepIsolateValue(output);
6333
- const scopeLabel = scopePath.length > 0 ? scopePath.join(".") : "";
6334
6906
  const candidates = plan.candidates ?? [];
6907
+ const needsGetterView = candidates.some((candidate) => {
6908
+ const descriptor = candidate.descriptor;
6909
+ if (typeof descriptor?.get !== "function") return false;
6910
+ if (!privateRow && descriptor.dependsOnPopulate?.length) return false;
6911
+ const dependsOn = Array.isArray(descriptor.dependsOn) ? descriptor.dependsOn : [];
6912
+ return dependsOn.every((dep) => typeof dep === "string" && !isAbsentDependency(output, dep));
6913
+ });
6914
+ let stableBase = needsGetterView ? deepIsolateValue(output) : void 0;
6915
+ const scopeLabel = scopePath.length > 0 ? scopePath.join(".") : "";
6335
6916
  const staged = /* @__PURE__ */ new Map();
6336
6917
  const runCandidate = async (candidate) => {
6337
6918
  const dependsOn = Array.isArray(candidate.descriptor?.dependsOn) ? candidate.descriptor.dependsOn : [];
6338
6919
  for (const dep of dependsOn) {
6339
- if (typeof dep !== "string" || isAbsentDependency(stableBase, dep)) return;
6920
+ if (typeof dep !== "string" || isAbsentDependency(stableBase ?? output, dep)) return;
6340
6921
  }
6341
6922
  const allowed = documentAuthorization ? await evaluateAuthorizedOutputField(documentAuthorization, binding, candidate.name) : await evaluateEffectiveFieldAuthorization({
6342
6923
  req: args.request,
@@ -6351,9 +6932,9 @@ async function finalizeSingleDoc(args, input) {
6351
6932
  if (typeof getter !== "function") return;
6352
6933
  const privateInputs = privateRow ? readVirtualPopulateInputs(privateRow, privateAddress, candidate.name) : candidate.descriptor.dependsOnPopulate?.length ? { available: false } : { available: true, populated: {} };
6353
6934
  if (!privateInputs.available) return;
6354
- const isolatedView = deepIsolateValue(stableBase);
6935
+ const isolatedView = deepIsolateValue(stableBase ??= deepIsolateValue(output));
6355
6936
  const virtualContext = {
6356
- ...scopeContext,
6937
+ ...deepIsolateValue(scopeContext),
6357
6938
  docPermissions: deepIsolateValue(docGrants)
6358
6939
  };
6359
6940
  const outcome = await runVirtualGetter({
@@ -6393,10 +6974,17 @@ async function finalizeSingleDoc(args, input) {
6393
6974
  }
6394
6975
  const eligiblePersisted = new Set(plan.outputPersistedFields ?? []);
6395
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
+ }
6396
6984
  const allowedPersisted = [];
6397
6985
  for (const field of eligiblePersisted) {
6398
6986
  if (documentAuthorization) {
6399
- if (plan.childPlans[field] || await evaluateAuthorizedOutputField(documentAuthorization, binding, field))
6987
+ if (plan.childPlans[field] || (staticDecisions ? staticDecisions.get(field) === true : await evaluateAuthorizedOutputField(documentAuthorization, binding, field)))
6400
6988
  allowedPersisted.push(field);
6401
6989
  continue;
6402
6990
  }
@@ -6444,12 +7032,25 @@ async function finalizeSingleDoc(args, input) {
6444
7032
  if (!(key in output)) continue;
6445
7033
  if (captured && !plan.childPlans[key]) {
6446
7034
  const path = [...binding.scopePath ?? [], key].join(".");
6447
- trimmed[key] = captured.configuration.catalog.referencePaths?.some((p) => matchesCatalogPattern(p, path)) ? copyAuthorizedReference(output[key], plan, path) : copyOutputValue(output[key], plan, path);
7035
+ trimmed[key] = captured.catalog.referencePaths?.some((p) => matchesCatalogPattern(p, path)) ? copyAuthorizedReference(output[key], plan, path) : copyOutputValue(output[key], plan, path);
6448
7036
  if (trimmed[key] === void 0) delete trimmed[key];
6449
7037
  } else trimmed[key] = output[key];
6450
7038
  }
6451
7039
  if (documentAuthorization) {
6452
- retainOutputMetadata(trimmed, metadataSource, captured.configuration, binding.scopePath ?? []);
7040
+ retainOutputMetadata(
7041
+ trimmed,
7042
+ metadataSource,
7043
+ copyAuthorizationValue(
7044
+ {
7045
+ documentPermissionField: snapshot.documentPermissionField,
7046
+ stripPermissionsField: snapshot.stripPermissionsField,
7047
+ exposedDocPermissionKeys: snapshot.exposedDocPermissionKeys,
7048
+ disableFieldPermissions: snapshot.disableFieldPermissions
7049
+ },
7050
+ true
7051
+ ),
7052
+ binding.scopePath ?? []
7053
+ );
6453
7054
  associateDocumentAuthorization(documentAuthorization, binding, trimmed);
6454
7055
  args.onFinalized?.(
6455
7056
  trimmed,
@@ -6458,9 +7059,13 @@ async function finalizeSingleDoc(args, input) {
6458
7059
  output: trimmed,
6459
7060
  outputAccess: args.outputAccess,
6460
7061
  authorization: plan.authorization,
6461
- stage: readDocumentAuthorization(documentAuthorization, binding).stage
7062
+ stage: readDocumentAuthorizationAccess(documentAuthorization, binding).stage
6462
7063
  })
6463
7064
  );
7065
+ if (staticDecisions) {
7066
+ assertFinalizerCall(args, prepared);
7067
+ readDocumentAuthorizationAccess(documentAuthorization, binding);
7068
+ }
6464
7069
  }
6465
7070
  void getRetainedAssociations;
6466
7071
  return trimmed;
@@ -6479,7 +7084,7 @@ async function finalizeModelOutput(args) {
6479
7084
  sharedGate: gate,
6480
7085
  resolvedLimit: limit
6481
7086
  };
6482
- return finalizeSingleDoc(internal, args.input);
7087
+ return finalizeSingleDoc(internal, args.input, prepareFinalizer(internal));
6483
7088
  }
6484
7089
  async function finalizeModelOutputs(args) {
6485
7090
  const gate = finalizerGate(args);
@@ -6488,16 +7093,24 @@ async function finalizeModelOutputs(args) {
6488
7093
  if ("documentAuthorizationStage" in args || documentAuthorizationStages && (documentAuthorizationStages.length !== inputs.length || new Set(documentAuthorizationStages).size !== inputs.length)) {
6489
7094
  authorizationError("list finalization requires a distinct document stage per row");
6490
7095
  }
7096
+ if (!inputs.length) return [];
7097
+ const internal = {
7098
+ ...rest,
7099
+ scopePath: [...rest.scopePath ?? rest.plan.scopePath ?? []],
7100
+ sharedGate: gate,
7101
+ resolvedLimit: limit
7102
+ };
7103
+ const prepared = prepareFinalizer(internal, inputs.length > 1);
6491
7104
  return mapWithConcurrencyLimit(inputs, limit, (input, index) => {
6492
- const internal = {
6493
- ...rest,
6494
- scopePath: [...rest.scopePath ?? rest.plan.scopePath ?? []],
6495
- onFinalized: rest.onFinalized ? (output, context) => rest.onFinalized(output, context, index) : void 0,
6496
- documentAuthorizationStage: documentAuthorizationStages?.[index],
6497
- sharedGate: gate,
6498
- resolvedLimit: limit
6499
- };
6500
- return finalizeSingleDoc(internal, input);
7105
+ return finalizeSingleDoc(
7106
+ {
7107
+ ...internal,
7108
+ onFinalized: rest.onFinalized ? (output, context) => rest.onFinalized(output, context, index) : void 0,
7109
+ documentAuthorizationStage: documentAuthorizationStages?.[index]
7110
+ },
7111
+ input,
7112
+ prepared
7113
+ );
6501
7114
  });
6502
7115
  }
6503
7116
  var isVirtualContainerValue3, getScopeVirtualsObject2, getScopeVirtualNames, getScopedPermissionSchema2, resolveGlobalPermissions, resolveDocPermissions, isAbsentDependency, __finalizeInternals;
@@ -6513,22 +7126,23 @@ var init_finalize_model_output = __esm({
6513
7126
  init_output_field_filter();
6514
7127
  init_field_authorization();
6515
7128
  init_field_catalog();
7129
+ init_output_projection();
6516
7130
  init_virtual_populate_execution();
6517
7131
  init_include_output();
6518
- isVirtualContainerValue3 = (value) => isPlainObject22(value) && "sub" in value;
7132
+ isVirtualContainerValue3 = (value) => isPlainObject23(value) && "sub" in value;
6519
7133
  getScopeVirtualsObject2 = (rootVirtuals, scopePath) => {
6520
- if (!rootVirtuals || !isPlainObject22(rootVirtuals)) return null;
7134
+ if (!rootVirtuals || !isPlainObject23(rootVirtuals)) return null;
6521
7135
  if (scopePath.length === 0) return rootVirtuals;
6522
7136
  let current = rootVirtuals;
6523
7137
  for (let i = 0; i < scopePath.length; i += 2) {
6524
7138
  const field = scopePath[i];
6525
7139
  const subMarker = scopePath[i + 1];
6526
7140
  if (!field || subMarker !== "sub") return null;
6527
- if (!isPlainObject22(current)) return null;
7141
+ if (!isPlainObject23(current)) return null;
6528
7142
  const container = current[field];
6529
7143
  if (!isVirtualContainerValue3(container)) return null;
6530
7144
  current = container.sub;
6531
- if (!isPlainObject22(current)) return null;
7145
+ if (!isPlainObject23(current)) return null;
6532
7146
  }
6533
7147
  return current;
6534
7148
  };
@@ -6541,11 +7155,11 @@ var init_finalize_model_output = __esm({
6541
7155
  return Object.entries(scopeVirtuals).filter(([, v]) => v !== void 0 && !isVirtualContainerValue3(v)).map(([k]) => k);
6542
7156
  };
6543
7157
  getScopedPermissionSchema2 = (root, scopePath) => {
6544
- if (!root || !isPlainObject22(root)) return null;
7158
+ if (!root || !isPlainObject23(root)) return null;
6545
7159
  if (scopePath.length === 0) return root;
6546
7160
  try {
6547
7161
  const scoped = get9(root, scopePath.join("."));
6548
- return isPlainObject22(scoped) ? scoped : null;
7162
+ return isPlainObject23(scoped) ? scoped : null;
6549
7163
  } catch {
6550
7164
  return null;
6551
7165
  }
@@ -6566,7 +7180,7 @@ var init_finalize_model_output = __esm({
6566
7180
  };
6567
7181
  resolveDocPermissions = async (args, isolatedForHook, scopeContext) => {
6568
7182
  if (args.docPermissions != null && typeof args.docPermissions === "object" && !Array.isArray(args.docPermissions)) {
6569
- const grants = args.docPermissions;
7183
+ const grants = deepIsolateValue(args.docPermissions);
6570
7184
  scopeContext.docPermissions = grants;
6571
7185
  return grants;
6572
7186
  }
@@ -6604,7 +7218,7 @@ var init_finalize_model_output = __esm({
6604
7218
  const grants = await args.sharedGate.run(
6605
7219
  () => hook.call(args.request, isolatedForHook, globalPerms, scopeContext)
6606
7220
  );
6607
- const normalized = isPlainObject22(grants) ? grants : {};
7221
+ const normalized = isPlainObject23(grants) ? grants : {};
6608
7222
  scopeContext.docPermissions = normalized;
6609
7223
  return normalized;
6610
7224
  }
@@ -6626,11 +7240,11 @@ var init_finalize_model_output = __esm({
6626
7240
  });
6627
7241
 
6628
7242
  // src/index.ts
6629
- 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";
6630
7244
 
6631
7245
  // src/middleware.ts
6632
7246
  import JsonRouter5 from "@web-ts-toolkit/express-json-router";
6633
- 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";
6634
7248
 
6635
7249
  // src/core.ts
6636
7250
  init_public_admission();
@@ -6665,7 +7279,7 @@ import {
6665
7279
  forEach as forEach3,
6666
7280
  get as get8,
6667
7281
  isArray as isArray9,
6668
- isPlainObject as isPlainObject18,
7282
+ isPlainObject as isPlainObject19,
6669
7283
  set as set6,
6670
7284
  uniq
6671
7285
  } from "@web-ts-toolkit/utils";
@@ -6790,7 +7404,7 @@ init_public_admission();
6790
7404
  // src/correlated-includes.ts
6791
7405
  init_request_complexity();
6792
7406
  init_sort_policy();
6793
- 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";
6794
7408
  var PARENT_MARKER_KEY = "$parent";
6795
7409
  var ESCAPE_WRAPPER_KEY = "$escape";
6796
7410
  var SUBQUERY_PAYLOAD_KEYS = /* @__PURE__ */ new Set(["$$sq", "$$date"]);
@@ -6801,10 +7415,10 @@ var FIELD_SEGMENT_PATTERN = /^[A-Za-z_][A-Za-z0-9_$]*$/;
6801
7415
  var ARRAY_INDEX_SEGMENT_PATTERN = /^(0|[1-9]\d*)$/;
6802
7416
  var ownKeys = (value) => Object.keys(value);
6803
7417
  function isParentRefMarker(value) {
6804
- 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;
6805
7419
  }
6806
7420
  function isEscapedParentRef(value) {
6807
- 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;
6808
7422
  }
6809
7423
  function hasMarkerKey(value) {
6810
7424
  return ownKeys(value).includes(PARENT_MARKER_KEY) || ownKeys(value).includes(ESCAPE_WRAPPER_KEY);
@@ -6823,12 +7437,12 @@ function containsParentMarkerShape(value) {
6823
7437
  const seen = /* @__PURE__ */ new Set();
6824
7438
  const visit = (current) => {
6825
7439
  if (isParentRefMarker(current) || isEscapedParentRef(current)) return true;
6826
- if (isArray6(current)) {
7440
+ if (isArray7(current)) {
6827
7441
  if (seen.has(current)) return false;
6828
7442
  seen.add(current);
6829
7443
  return current.some(visit);
6830
7444
  }
6831
- if (isPlainObject15(current)) {
7445
+ if (isPlainObject17(current)) {
6832
7446
  if (seen.has(current)) return false;
6833
7447
  seen.add(current);
6834
7448
  if (hasMarkerKey(current)) return true;
@@ -6858,7 +7472,7 @@ function scanTemplateValueNode(value, path, issues) {
6858
7472
  }
6859
7473
  return;
6860
7474
  }
6861
- if (isPlainObject15(value)) {
7475
+ if (isPlainObject17(value)) {
6862
7476
  if (hasMarkerKey(value)) {
6863
7477
  issues.push({
6864
7478
  message: 'Malformed $parent reference: objects carrying $parent must be exactly { "$parent": "<field>" }',
@@ -6869,7 +7483,7 @@ function scanTemplateValueNode(value, path, issues) {
6869
7483
  scanTemplateObjectEntries(value, path, issues);
6870
7484
  return;
6871
7485
  }
6872
- if (isArray6(value)) {
7486
+ if (isArray7(value)) {
6873
7487
  value.forEach((item, index) => scanTemplateValueNode(item, [...path, index], issues));
6874
7488
  }
6875
7489
  }
@@ -6910,7 +7524,7 @@ function scanTemplateObjectEntries(obj, basePath, issues) {
6910
7524
  continue;
6911
7525
  }
6912
7526
  if (LOGICAL_CLAUSE_KEYS.has(key)) {
6913
- if (!isArray6(child)) {
7527
+ if (!isArray7(child)) {
6914
7528
  scanTemplateValueNode(child, childPath, issues);
6915
7529
  continue;
6916
7530
  }
@@ -6923,7 +7537,7 @@ function scanTemplateObjectEntries(obj, basePath, issues) {
6923
7537
  });
6924
7538
  return;
6925
7539
  }
6926
- if (isPlainObject15(clause)) {
7540
+ if (isPlainObject17(clause)) {
6927
7541
  scanTemplateObjectEntries(clause, clausePath, issues);
6928
7542
  }
6929
7543
  });
@@ -6934,7 +7548,7 @@ function scanTemplateObjectEntries(obj, basePath, issues) {
6934
7548
  }
6935
7549
  function validateCorrelatedFilterTemplate(filter2) {
6936
7550
  const issues = [];
6937
- if (!isPlainObject15(filter2)) {
7551
+ if (!isPlainObject17(filter2)) {
6938
7552
  issues.push({ message: "Correlated include filter must be an object", path: [] });
6939
7553
  return issues;
6940
7554
  }
@@ -6977,13 +7591,13 @@ function collectFilterReferencePaths(filter2) {
6977
7591
  return;
6978
7592
  }
6979
7593
  if (isEscapedParentRef(value)) return;
6980
- if (isArray6(value)) {
7594
+ if (isArray7(value)) {
6981
7595
  if (seen.has(value)) return;
6982
7596
  seen.add(value);
6983
7597
  value.forEach(visitValue);
6984
7598
  return;
6985
7599
  }
6986
- if (isPlainObject15(value)) {
7600
+ if (isPlainObject17(value)) {
6987
7601
  if (seen.has(value)) return;
6988
7602
  seen.add(value);
6989
7603
  for (const [key, child] of Object.entries(value)) {
@@ -7029,7 +7643,7 @@ function getOwnPathValue(parent, path) {
7029
7643
  return current;
7030
7644
  }
7031
7645
  function cloneSubstitutedValue(value) {
7032
- if (isPlainObject15(value) || isArray6(value)) return cloneDeep(value);
7646
+ if (isPlainObject17(value) || isArray7(value)) return cloneDeep(value);
7033
7647
  return value;
7034
7648
  }
7035
7649
  function literalParentRefObject(path) {
@@ -7070,7 +7684,7 @@ function resolveObjectEntries(obj, parent) {
7070
7684
  continue;
7071
7685
  }
7072
7686
  if (LOGICAL_CLAUSE_KEYS.has(key)) {
7073
- if (!isArray6(child)) {
7687
+ if (!isArray7(child)) {
7074
7688
  out[key] = resolveValueNode(child, parent, false);
7075
7689
  continue;
7076
7690
  }
@@ -7078,7 +7692,7 @@ function resolveObjectEntries(obj, parent) {
7078
7692
  if (isParentRefMarker(clause) || isEscapedParentRef(clause)) {
7079
7693
  throw new CorrelatedReferenceError(`Unsupported $parent reference as a direct ${key} clause`);
7080
7694
  }
7081
- if (!isPlainObject15(clause)) return cloneSubstitutedValue(clause);
7695
+ if (!isPlainObject17(clause)) return cloneSubstitutedValue(clause);
7082
7696
  return resolveObjectEntries(clause, parent);
7083
7697
  });
7084
7698
  continue;
@@ -7107,10 +7721,10 @@ function resolveValueNode(template, parent, bare) {
7107
7721
  }
7108
7722
  const value = getOwnPathValue(parent, path);
7109
7723
  if (value === void 0 || value === null) throw UNRESOLVABLE;
7110
- if (bare && isPlainObject15(value)) return { $eq: cloneDeep(value) };
7724
+ if (bare && isPlainObject17(value)) return { $eq: cloneDeep(value) };
7111
7725
  return cloneSubstitutedValue(value);
7112
7726
  }
7113
- if (isPlainObject15(template)) {
7727
+ if (isPlainObject17(template)) {
7114
7728
  if (hasMarkerKey(template)) {
7115
7729
  throw new CorrelatedReferenceError(
7116
7730
  'Malformed $parent reference: objects carrying $parent must be exactly { "$parent": "<field>" }'
@@ -7118,7 +7732,7 @@ function resolveValueNode(template, parent, bare) {
7118
7732
  }
7119
7733
  return resolveObjectEntries(template, parent);
7120
7734
  }
7121
- if (isArray6(template)) {
7735
+ if (isArray7(template)) {
7122
7736
  return template.map((item) => resolveValueNode(item, parent, false));
7123
7737
  }
7124
7738
  return template;
@@ -7152,7 +7766,7 @@ function resolveCorrelatedIdTemplate(id, parent) {
7152
7766
  }
7153
7767
  function resolveCorrelatedFilterTemplate(filter2, parent) {
7154
7768
  try {
7155
- if (!isPlainObject15(filter2) || isParentRefMarker(filter2) || isEscapedParentRef(filter2)) {
7769
+ if (!isPlainObject17(filter2) || isParentRefMarker(filter2) || isEscapedParentRef(filter2)) {
7156
7770
  throw new CorrelatedReferenceError("Correlated include filter must be an object");
7157
7771
  }
7158
7772
  return { status: "resolved", filter: resolveObjectEntries(filter2, parent) };
@@ -7167,7 +7781,7 @@ function validateExpandedCorrelatedOperands(expanded, limits) {
7167
7781
  var MAX_NESTED_INCLUDE_DEPTH = 10;
7168
7782
  function validateCorrelatedArgsShape(args, op, depth) {
7169
7783
  if (args === void 0) return [];
7170
- if (!isPlainObject15(args)) return ["Correlated include args must be an object"];
7784
+ if (!isPlainObject17(args)) return ["Correlated include args must be an object"];
7171
7785
  const record3 = args;
7172
7786
  const allowed = op === "list" ? /* @__PURE__ */ new Set(["select", "sort", "skip", "limit", "page", "pageSize", "include"]) : /* @__PURE__ */ new Set(["select", "sort", "include"]);
7173
7787
  for (const key of Object.keys(record3)) {
@@ -7189,7 +7803,7 @@ function validateCorrelatedArgsShape(args, op, depth) {
7189
7803
  return [];
7190
7804
  }
7191
7805
  function validateCorrelatedIncludeShape(entry, depth = 0) {
7192
- if (!isPlainObject15(entry)) return ["Correlated include must be an object"];
7806
+ if (!isPlainObject17(entry)) return ["Correlated include must be an object"];
7193
7807
  const record3 = entry;
7194
7808
  if (record3.mode !== "correlated") return ['Correlated include mode must be "correlated"'];
7195
7809
  if (typeof record3.model !== "string" || record3.model.length === 0)
@@ -7202,7 +7816,7 @@ function validateCorrelatedIncludeShape(entry, depth = 0) {
7202
7816
  if ("localField" in record3 || "foreignField" in record3) {
7203
7817
  return ["Correlated includes must not carry localField or foreignField"];
7204
7818
  }
7205
- 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)) {
7206
7820
  return ["Correlated include options must be absent or empty"];
7207
7821
  }
7208
7822
  const hasId = record3.id !== void 0;
@@ -7224,7 +7838,7 @@ function validateCorrelatedIncludeShape(entry, depth = 0) {
7224
7838
  return validateCorrelatedArgsShape(record3.args, record3.op, depth);
7225
7839
  }
7226
7840
  function isCorrelatedInclude(value) {
7227
- return isPlainObject15(value) && value.mode === "correlated";
7841
+ return isPlainObject17(value) && value.mode === "correlated";
7228
7842
  }
7229
7843
 
7230
7844
  // src/services/base.ts
@@ -7510,9 +8124,9 @@ function createServiceExecution(receiver, access, authorization, applicability =
7510
8124
  receiver,
7511
8125
  binding,
7512
8126
  authorization: call,
7513
- access: readServiceAuthorization(call, binding).access,
8127
+ access: readServiceAuthorizationAccess(call, binding),
7514
8128
  family: execution,
7515
- hydration: resolveHydration(readServiceAuthorization(call, binding).configuration, hydration)
8129
+ hydration: resolveHydration(readServiceAuthorizationHydration(call, binding), hydration)
7516
8130
  })
7517
8131
  );
7518
8132
  return execution;
@@ -7523,7 +8137,7 @@ function resolveHydration(configuration, source) {
7523
8137
  }
7524
8138
  function withExecutionHydration(receiver, parent, source) {
7525
8139
  const record3 = readServiceExecution(receiver, parent);
7526
- const { configuration } = readServiceAuthorization(record3.authorization, record3.binding);
8140
+ const configuration = readServiceAuthorizationHydration(record3.authorization, record3.binding);
7527
8141
  const execution = Object.freeze(/* @__PURE__ */ Object.create(null));
7528
8142
  executions.set(execution, Object.freeze({ ...record3, hydration: resolveHydration(configuration, source) }));
7529
8143
  return execution;
@@ -7560,7 +8174,7 @@ function deriveServiceExecution(receiver, parent, access, applicability = "servi
7560
8174
  const execution = Object.freeze(/* @__PURE__ */ Object.create(null));
7561
8175
  executions.set(
7562
8176
  execution,
7563
- Object.freeze({ ...record3, authorization: call, access: readServiceAuthorization(call, record3.binding).access })
8177
+ Object.freeze({ ...record3, authorization: call, access: readServiceAuthorizationAccess(call, record3.binding) })
7564
8178
  );
7565
8179
  return execution;
7566
8180
  }
@@ -7961,20 +8575,20 @@ var copyAuthorizedOutput = (value) => {
7961
8575
  transferDocumentAuthorizationGraph(value, copy);
7962
8576
  return copy;
7963
8577
  };
7964
- var isVirtualContainerValueForGuard = (value) => isPlainObject18(value) && "sub" in value;
8578
+ var isVirtualContainerValueForGuard = (value) => isPlainObject19(value) && "sub" in value;
7965
8579
  var getScopeVirtualsForGuard = (rootVirtuals, scopePath) => {
7966
- if (!rootVirtuals || !isPlainObject18(rootVirtuals)) return null;
8580
+ if (!rootVirtuals || !isPlainObject19(rootVirtuals)) return null;
7967
8581
  if (scopePath.length === 0) return rootVirtuals;
7968
8582
  let current = rootVirtuals;
7969
8583
  for (let i = 0; i < scopePath.length; i += 2) {
7970
8584
  const field = scopePath[i];
7971
8585
  const subMarker = scopePath[i + 1];
7972
8586
  if (!field || subMarker !== "sub") return null;
7973
- if (!isPlainObject18(current)) return null;
8587
+ if (!isPlainObject19(current)) return null;
7974
8588
  const container = current[field];
7975
8589
  if (!isVirtualContainerValueForGuard(container)) return null;
7976
8590
  current = container.sub;
7977
- if (!isPlainObject18(current)) return null;
8591
+ if (!isPlainObject19(current)) return null;
7978
8592
  }
7979
8593
  return current;
7980
8594
  };
@@ -8040,7 +8654,7 @@ var sanitizeSubScopeVirtualKeys = (data, snapshot, sub) => {
8040
8654
  for (const entry of value) stripScope(entry, currentScope);
8041
8655
  return;
8042
8656
  }
8043
- if (!isPlainObject18(value)) return;
8657
+ if (!isPlainObject19(value)) return;
8044
8658
  const record3 = value;
8045
8659
  const leaves = getScopeVirtualLeafNames(snapshot, currentScope);
8046
8660
  for (const leaf of leaves) {
@@ -8053,7 +8667,7 @@ var sanitizeSubScopeVirtualKeys = (data, snapshot, sub) => {
8053
8667
  for (const key of Object.keys(record3)) {
8054
8668
  if (leaves.has(key) || containers.has(key)) continue;
8055
8669
  const child = record3[key];
8056
- if (Array.isArray(child) || isPlainObject18(child)) {
8670
+ if (Array.isArray(child) || isPlainObject19(child)) {
8057
8671
  stripScope(child, currentScope);
8058
8672
  }
8059
8673
  }
@@ -8065,7 +8679,7 @@ var LOGICAL_FILTER_KEYS = /* @__PURE__ */ new Set(["$and", "$or", "$nor"]);
8065
8679
  var isOperatorKey = (key) => key.startsWith("$");
8066
8680
  var REMOVED_VIRTUAL_FILTER = /* @__PURE__ */ Symbol("removed virtual filter clause");
8067
8681
  var rewriteFilterObject = (value, visit) => {
8068
- if (!isPlainObject18(value)) return value;
8682
+ if (!isPlainObject19(value)) return value;
8069
8683
  let changed = false;
8070
8684
  const entries = [];
8071
8685
  for (const [key, child] of Object.entries(value)) {
@@ -8096,7 +8710,7 @@ var resolveVirtualFilterField = (path, scope2) => {
8096
8710
  if (!Object.hasOwn(scope2, segment) || scope2[segment] === void 0) return null;
8097
8711
  const definition = scope2[segment];
8098
8712
  if (!isVirtualContainerValueForGuard(definition)) return REMOVED_VIRTUAL_FILTER;
8099
- scope2 = isPlainObject18(definition.sub) ? definition.sub : null;
8713
+ scope2 = isPlainObject19(definition.sub) ? definition.sub : null;
8100
8714
  inContainer = true;
8101
8715
  }
8102
8716
  return scope2;
@@ -8108,7 +8722,7 @@ var stripVirtualFilterOperator = (key, value, scope2) => {
8108
8722
  }
8109
8723
  if (key === "$all") {
8110
8724
  return rewriteFilterClauses(value, (entry) => {
8111
- 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;
8112
8726
  return rewriteFilterObject(entry, (operator, operand) => stripVirtualFilterOperator(operator, operand, scope2));
8113
8727
  });
8114
8728
  }
@@ -8123,7 +8737,7 @@ var stripVirtualFilterQuery = (value, scope2, element = false) => {
8123
8737
  if (isOperatorKey(key)) return element ? stripVirtualFilterOperator(key, child, scope2) : child;
8124
8738
  const fieldScope = resolveVirtualFilterField(key, scope2);
8125
8739
  if (fieldScope === REMOVED_VIRTUAL_FILTER) return REMOVED_VIRTUAL_FILTER;
8126
- if (!fieldScope || !isPlainObject18(child)) return child;
8740
+ if (!fieldScope || !isPlainObject19(child)) return child;
8127
8741
  if (Object.keys(child).some(isOperatorKey)) {
8128
8742
  return rewriteFilterObject(
8129
8743
  child,
@@ -8147,7 +8761,7 @@ function getCorrelatedTemplateDepth(includes) {
8147
8761
  const visit = (entries, depth) => {
8148
8762
  const list = castArray2(entries).filter(Boolean);
8149
8763
  for (const entry of list) {
8150
- if (!isPlainObject18(entry)) continue;
8764
+ if (!isPlainObject19(entry)) continue;
8151
8765
  max = Math.max(max, depth);
8152
8766
  const nested = entry.args?.include;
8153
8767
  if (nested !== void 0) {
@@ -8176,7 +8790,7 @@ function validateClientFilter(filter2) {
8176
8790
  value.forEach((item, index) => visit(item, `${path}[${index}]`));
8177
8791
  return;
8178
8792
  }
8179
- if (!isPlainObject18(value)) return;
8793
+ if (!isPlainObject19(value)) return;
8180
8794
  Object.entries(value).forEach(([key, child]) => {
8181
8795
  const nextPath = path ? `${path}.${key}` : key;
8182
8796
  if (blockedOperators.has(key)) {
@@ -8458,9 +9072,9 @@ var Base = class {
8458
9072
  const walk = (node, prefix) => {
8459
9073
  for (const [key, value] of Object.entries(node)) {
8460
9074
  if (value === void 0) continue;
8461
- if (isPlainObject18(value) && "sub" in value) {
9075
+ if (isPlainObject19(value) && "sub" in value) {
8462
9076
  const sub = value.sub;
8463
- if (isPlainObject18(sub)) walk(sub, prefix ? `${prefix}.${key}` : key);
9077
+ if (isPlainObject19(sub)) walk(sub, prefix ? `${prefix}.${key}` : key);
8464
9078
  continue;
8465
9079
  }
8466
9080
  out.push(prefix ? `${prefix}.${key}` : key);
@@ -8513,7 +9127,7 @@ var Base = class {
8513
9127
  this.throwClientRequestError("bad_request" /* BadRequest */, `Model ${modelName} not found`);
8514
9128
  }
8515
9129
  for (const entry of entries) {
8516
- if (!isPlainObject18(entry)) continue;
9130
+ if (!isPlainObject19(entry)) continue;
8517
9131
  const models = visited.get(entry) ?? /* @__PURE__ */ new Set();
8518
9132
  if (models.has(modelName)) continue;
8519
9133
  models.add(modelName);
@@ -9132,7 +9746,7 @@ import {
9132
9746
  get as get13,
9133
9747
  isArray as isArray10,
9134
9748
  isBoolean as isBoolean4,
9135
- isPlainObject as isPlainObject25,
9749
+ isPlainObject as isPlainObject26,
9136
9750
  omit,
9137
9751
  set as set10,
9138
9752
  uniq as uniq2,
@@ -9233,7 +9847,7 @@ var model_default = Model;
9233
9847
  // src/acl/distinct-field-authorization.ts
9234
9848
  init_field_authorization();
9235
9849
  init_field_catalog();
9236
- import { isPlainObject as isPlainObject19 } from "@web-ts-toolkit/utils";
9850
+ import { isPlainObject as isPlainObject20 } from "@web-ts-toolkit/utils";
9237
9851
  var schemaVariants = (schema) => Object.values(schema.discriminators ?? {});
9238
9852
  var scalarTypes = /* @__PURE__ */ new Set([
9239
9853
  "String",
@@ -9313,8 +9927,8 @@ function isDistinctFieldAuthorized(args) {
9313
9927
  if (path !== field && !path.startsWith(`${field}.`) && !field.startsWith(`${path}.`)) continue;
9314
9928
  if (path.startsWith(`${field}.`) && (!eligible(path) || !schemaShape(schema, path) || !granted(path)))
9315
9929
  return false;
9316
- if (isPlainObject19(raw) && raw.sub !== void 0) {
9317
- 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;
9318
9932
  }
9319
9933
  }
9320
9934
  return true;
@@ -9492,7 +10106,7 @@ init_populate_target();
9492
10106
 
9493
10107
  // src/helpers/apply-update.ts
9494
10108
  init_lib();
9495
- 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";
9496
10110
  function applyUpdate(target, data, allowedFields) {
9497
10111
  const wholeFields = /* @__PURE__ */ new Set();
9498
10112
  const partialContainers = /* @__PURE__ */ new Set();
@@ -9512,7 +10126,7 @@ function applyUpdate(target, data, allowedFields) {
9512
10126
  const apply = (values, prefix = "") => {
9513
10127
  for (const [key, value] of Object.entries(values)) {
9514
10128
  const path = prefix ? `${prefix}.${key}` : key;
9515
- 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))) {
9516
10130
  apply(value, path);
9517
10131
  } else if (isDocument2(target)) {
9518
10132
  target.set(path, value);
@@ -9529,7 +10143,7 @@ init_document();
9529
10143
  init_request_work();
9530
10144
  init_logger_helpers();
9531
10145
  init_request_complexity();
9532
- 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";
9533
10147
  import { mongo as mongo5 } from "mongoose";
9534
10148
 
9535
10149
  // src/acl/select-resolution.ts
@@ -9646,7 +10260,7 @@ init_field_catalog();
9646
10260
  init_service_authorization();
9647
10261
  var own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
9648
10262
  var inside = (path, root) => path === root || path.startsWith(`${root}.`);
9649
- var record2 = (value) => isPlainObject24(value);
10263
+ var record2 = (value) => isPlainObject25(value);
9650
10264
  function inputValue(value) {
9651
10265
  if (typeof value === "function" || typeof value === "symbol") {
9652
10266
  authorizationError("input values must be persisted data, not functions or symbols");
@@ -10648,7 +11262,8 @@ var Service = class extends Base {
10648
11262
  async finalizeDirectOutput(args) {
10649
11263
  const { plan, context } = args;
10650
11264
  const { authorization, authorizationBinding: binding } = plan;
10651
- const { access, configuration } = readServiceAuthorization(authorization, binding);
11265
+ const access = readServiceAuthorizationAccess(authorization, binding);
11266
+ const configuration = readServiceOutputMetadata(authorization, binding);
10652
11267
  const source = getIncludeSource(args.doc);
10653
11268
  const snapshot = isolateDocForOutput(source);
10654
11269
  for (const key of Object.keys(snapshot))
@@ -11072,7 +11687,7 @@ var Service = class extends Base {
11072
11687
  if (this.isScalarPopulateValue(rawTarget)) return rawTarget;
11073
11688
  const isDoc = (() => {
11074
11689
  try {
11075
- if (isPlainObject25(rawTarget)) return true;
11690
+ if (isPlainObject26(rawTarget)) return true;
11076
11691
  const maybe = rawTarget;
11077
11692
  if (maybe && typeof maybe === "object" && "_doc" in maybe) return true;
11078
11693
  if (maybe && typeof maybe.toObject === "function") return true;
@@ -13475,7 +14090,7 @@ init_helpers();
13475
14090
 
13476
14091
  // src/processors.ts
13477
14092
  init_permissions_alias();
13478
- 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";
13479
14094
  function cloneProcessorValue(value) {
13480
14095
  const copy = cloneDeep5(value);
13481
14096
  copyPermissionsAliasGraph(value, copy);
@@ -13515,7 +14130,7 @@ function resolveLeafParents(obj, src) {
13515
14130
  for (let ind = 0; ind < segs.length - 1; ind += 1) {
13516
14131
  const seg = segs[ind];
13517
14132
  targets = targets.reduce((ret, target) => {
13518
- if (!isPlainObject26(target)) return ret;
14133
+ if (!isPlainObject27(target)) return ret;
13519
14134
  const targetObject = target;
13520
14135
  const next = targetObject[seg];
13521
14136
  if (isArray11(next)) {
@@ -13529,7 +14144,7 @@ function resolveLeafParents(obj, src) {
13529
14144
  const leaf = segs[segs.length - 1];
13530
14145
  const pairs = [];
13531
14146
  forEach5(targets, (target) => {
13532
- if (!isPlainObject26(target)) return;
14147
+ if (!isPlainObject27(target)) return;
13533
14148
  pairs.push({ parent: target, leaf });
13534
14149
  });
13535
14150
  return pairs;
@@ -13550,7 +14165,7 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
13550
14165
  forEach5(segs, (seg, ind) => {
13551
14166
  if (segs.length === ind + 1) {
13552
14167
  forEach5(targets, (target) => {
13553
- if (!isPlainObject26(target)) return;
14168
+ if (!isPlainObject27(target)) return;
13554
14169
  const targetObject = target;
13555
14170
  const leaf = targetObject[seg];
13556
14171
  const sourceForDest = leaf;
@@ -13558,7 +14173,7 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
13558
14173
  if (isArray11(leaf)) {
13559
14174
  if (leaf.length === 0) {
13560
14175
  depopulated = [];
13561
- } else if (leaf.every((item) => isPlainObject26(item))) {
14176
+ } else if (leaf.every((item) => isPlainObject27(item))) {
13562
14177
  depopulated = map(leaf, idField).map((id, i) => {
13563
14178
  if (id === void 0) {
13564
14179
  failMissingId(`${src}[${i}]`);
@@ -13568,7 +14183,7 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
13568
14183
  } else {
13569
14184
  return;
13570
14185
  }
13571
- } else if (isPlainObject26(leaf)) {
14186
+ } else if (isPlainObject27(leaf)) {
13572
14187
  const id = get14(leaf, idField);
13573
14188
  if (id === void 0) {
13574
14189
  failMissingId(src);
@@ -13582,7 +14197,7 @@ var copyAndDepopulate = (docObject, operations, options = { mutable: true, idFie
13582
14197
  });
13583
14198
  } else {
13584
14199
  targets = targets.reduce((ret, target) => {
13585
- if (!isPlainObject26(target)) return ret;
14200
+ if (!isPlainObject27(target)) return ret;
13586
14201
  const targetObject = target;
13587
14202
  const next = targetObject[seg];
13588
14203
  if (isArray11(next)) {
@@ -13688,7 +14303,7 @@ var countPaths = (docObject, operations, options = { mutable: true }) => {
13688
14303
  let count;
13689
14304
  if (isArray11(leafValue)) {
13690
14305
  count = leafValue.length;
13691
- } else if (isPlainObject26(leafValue)) {
14306
+ } else if (isPlainObject27(leafValue)) {
13692
14307
  count = Object.keys(leafValue).length;
13693
14308
  } else if (leafValue === null || typeof leafValue === "undefined") {
13694
14309
  count = 0;
@@ -14330,12 +14945,12 @@ function guard(condition) {
14330
14945
  const permissions = req[PERMISSIONS];
14331
14946
  let cond = condition;
14332
14947
  let phas = (key) => permissions.has(key);
14333
- if (isPlainObject27(condition)) {
14948
+ if (isPlainObject28(condition)) {
14334
14949
  const { modelName, id, condition: _cond } = condition;
14335
14950
  const svc = req.macl.getPublicService(modelName);
14336
14951
  const select = getModelOption(modelName, `alwaysSelectFields.read`, void 0);
14337
14952
  let _id = isString7(id) ? id : null;
14338
- if (isPlainObject27(id)) {
14953
+ if (isPlainObject28(id)) {
14339
14954
  const { type = "param", key } = id;
14340
14955
  if (type === "param") {
14341
14956
  const paramValue = req.params[key];
@@ -14377,7 +14992,7 @@ import express2 from "express";
14377
14992
 
14378
14993
  // src/routers/model-router.ts
14379
14994
  import JsonRouter8 from "@web-ts-toolkit/express-json-router";
14380
- 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";
14381
14996
  init_logger_helpers();
14382
14997
  init_runtime();
14383
14998
  init_runtime_context();
@@ -14511,7 +15126,7 @@ import JsonRouter7 from "@web-ts-toolkit/express-json-router";
14511
15126
 
14512
15127
  // src/validation/common.ts
14513
15128
  import { z as z2 } from "zod";
14514
- import { isPlainObject as isPlainObject28 } from "@web-ts-toolkit/utils";
15129
+ import { isPlainObject as isPlainObject29 } from "@web-ts-toolkit/utils";
14515
15130
 
14516
15131
  // src/validation/public-admission-schema.ts
14517
15132
  init_public_admission();
@@ -14640,7 +15255,7 @@ var correlatedFilterSchema = z2.record(z2.string(), z2.unknown()).superRefine((f
14640
15255
  }
14641
15256
  });
14642
15257
  var correlatedEmptyOptionsSchema = z2.unknown().refine(
14643
- (value) => value === void 0 || isPlainObject28(value) && Object.keys(value).length === 0,
15258
+ (value) => value === void 0 || isPlainObject29(value) && Object.keys(value).length === 0,
14644
15259
  "Correlated include options must be absent or empty"
14645
15260
  ).optional();
14646
15261
  var correlatedPathSchema = z2.string().min(1).superRefine((path, ctx) => {
@@ -14677,7 +15292,7 @@ var correlatedListArgsSchema = z2.object({
14677
15292
  include: z2.lazy(() => correlatedNestedIncludeSchema).optional()
14678
15293
  }).strict().superRefine((args, ctx) => checkArgsMarkers(args.select, args.sort, ctx));
14679
15294
  var correlatedCountArgsSchema = z2.unknown().refine(
14680
- (value) => value === void 0 || isPlainObject28(value) && Object.keys(value).length === 0,
15295
+ (value) => value === void 0 || isPlainObject29(value) && Object.keys(value).length === 0,
14681
15296
  "Count includes accept no args"
14682
15297
  ).optional();
14683
15298
  var correlatedReadByIdSchema = z2.object({
@@ -14730,7 +15345,7 @@ var correlatedNestedIncludeSchema = z2.union([includeItemSchema, z2.array(includ
14730
15345
  var rejectDuplicateCorrelatedPaths = (items, ctx) => {
14731
15346
  const seen = /* @__PURE__ */ new Set();
14732
15347
  items.forEach((item, index) => {
14733
- if (isPlainObject28(item) && item.mode === "correlated" && typeof item.path === "string") {
15348
+ if (isPlainObject29(item) && item.mode === "correlated" && typeof item.path === "string") {
14734
15349
  if (seen.has(item.path)) {
14735
15350
  ctx.addIssue({
14736
15351
  code: z2.ZodIssueCode.custom,
@@ -16731,7 +17346,7 @@ var ModelRouter = class _ModelRouter {
16731
17346
  value
16732
17347
  );
16733
17348
  }
16734
- if (arguments.length === 1 && isPlainObject29(keyOrOptions)) {
17349
+ if (arguments.length === 1 && isPlainObject30(keyOrOptions)) {
16735
17350
  assertMutableRouterOptions("model", keyOrOptions);
16736
17351
  this.runtime.setModelOptions(
16737
17352
  this.modelName,
@@ -17265,7 +17880,7 @@ var RootRouter = class {
17265
17880
 
17266
17881
  // src/routers/data-router.ts
17267
17882
  import JsonRouter10 from "@web-ts-toolkit/express-json-router";
17268
- 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";
17269
17884
  init_runtime();
17270
17885
  init_helpers();
17271
17886
  init_schemas();
@@ -17481,7 +18096,7 @@ var DataRouter = class {
17481
18096
  value
17482
18097
  );
17483
18098
  }
17484
- if (arguments.length === 1 && isPlainObject30(keyOrOptions)) {
18099
+ if (arguments.length === 1 && isPlainObject31(keyOrOptions)) {
17485
18100
  assertMutableRouterOptions("data", keyOrOptions);
17486
18101
  this.runtime.setDataOptions(this.dataName, keyOrOptions);
17487
18102
  }
@@ -17640,7 +18255,7 @@ function createRuntimeApi(runtime) {
17640
18255
  if (arguments.length === 2 && isString10(keyOrOptions)) {
17641
18256
  return runtime.setGlobalOption(keyOrOptions, value);
17642
18257
  }
17643
- if (arguments.length === 1 && isPlainObject31(keyOrOptions)) {
18258
+ if (arguments.length === 1 && isPlainObject32(keyOrOptions)) {
17644
18259
  return runtime.setGlobalOptions(keyOrOptions);
17645
18260
  }
17646
18261
  };