@sanity/validation 6.23.0-next.7 → 6.24.0-next.111

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.
@@ -1,5 +1,5 @@
1
1
  import { isInternalValidator, markInternalValidator } from "@sanity/schema/_internal";
2
- import { isArrayOfBlocksSchemaType, isArrayOfObjectsSchemaType, isKeyedObject, isReference, isSlug, isTypedObject } from "@sanity/types";
2
+ import { isArrayOfBlocksSchemaType, isArrayOfObjectsSchemaType, isKeyedObject, isReference, isReferenceSchemaType, isSlug, isTypedObject } from "@sanity/types";
3
3
  import { createClientConcurrencyLimiter } from "@sanity/util/client";
4
4
  import { ConcurrencyLimiter } from "@sanity/util/concurrency-limiter";
5
5
  import { dequal } from "dequal/lite";
@@ -7,12 +7,13 @@ import flatten from "lodash-es/flatten.js";
7
7
  import { Observable } from "rxjs";
8
8
  import { map } from "rxjs/operators";
9
9
  import { createInstance } from "i18next";
10
- import { Rule as Rule$1 } from "@sanity/schema";
10
+ import { Rule as Rule$2 } from "@sanity/schema";
11
11
  import get from "lodash-es/get.js";
12
12
  import isPlainObject from "lodash-es/isPlainObject.js";
13
13
  import * as legacyDateFormat from "@sanity/util/legacyDateFormat";
14
14
  import { getPublishedId, getVersionId, getVersionNameFromId, isVersionId } from "@sanity/id-utils";
15
15
  import memoize from "lodash-es/memoize.js";
16
+ import { accepts } from "@sanity/util/accepts";
16
17
  /** Machine-readable codes emitted by built-in document validation. @beta */
17
18
  const validationMarkerCodes = {
18
19
  arrayDuplicateItem: "array.duplicate-item",
@@ -38,6 +39,7 @@ const validationMarkerCodes = {
38
39
  objectUnknownField: "object.unknown-field",
39
40
  referenceInvalid: "reference.invalid",
40
41
  referenceNotPublished: "reference.not-published",
42
+ referenceTargetTypeMismatch: "reference.target-type-mismatch",
41
43
  ruleAllFailed: "rule.all-failed",
42
44
  ruleEitherFailed: "rule.either-failed",
43
45
  slugInvalidType: "slug.invalid-type",
@@ -99,6 +101,7 @@ const validationLocaleStrings = {
99
101
  "object.not-media-library-asset": "Must be a reference to a Media Library asset",
100
102
  "object.not-reference": "Must be a reference to a document",
101
103
  "object.reference-not-published": "Referenced document must be published",
104
+ "object.reference-target-type-mismatch": "Referenced document has type \"{{actualType}}\"; expected one of: {{allowedTypes}}",
102
105
  "slug.missing-current": "Slug must have a value",
103
106
  "slug.not-object": "Slug must be an object",
104
107
  "slug.not-unique": "Slug is already in use",
@@ -145,79 +148,6 @@ function resolveConditionalProperty(property, context) {
145
148
  path
146
149
  }) === !0;
147
150
  }
148
- function hasPendingChecks(batch) {
149
- for (let checks of batch.values()) if (checks.some((check) => !check.settled)) return !0;
150
- return !1;
151
- }
152
- function settleCheck(check, result) {
153
- check.settled || (check.settled = !0, check.signal && check.onAbort && check.signal.removeEventListener("abort", check.onAbort), "error" in result ? check.reject(result.error) : check.resolve(result.exists));
154
- }
155
- function createBatchedGetDocumentExists(client, defaultSignal) {
156
- let buffer = /* @__PURE__ */ new Map(), queuedBatches = [], bufferTimer, draining = !1, activeRequest, rejectBatch = (batch, reason) => {
157
- for (let checks of batch.values()) for (let check of checks) settleCheck(check, { error: reason });
158
- }, rejectPending = (reason) => {
159
- bufferTimer !== void 0 && clearTimeout(bufferTimer), bufferTimer = void 0, rejectBatch(buffer, reason), buffer = /* @__PURE__ */ new Map();
160
- for (let batch of queuedBatches.splice(0)) rejectBatch(batch, reason);
161
- }, flush = () => {
162
- bufferTimer !== void 0 && clearTimeout(bufferTimer), bufferTimer = void 0, buffer.size !== 0 && (queuedBatches.push(buffer), buffer = /* @__PURE__ */ new Map(), drain());
163
- }, scheduleFlush = () => {
164
- buffer.size >= 100 ? flush() : bufferTimer === void 0 && (bufferTimer = setTimeout(flush, 250));
165
- };
166
- async function drain() {
167
- if (!draining) {
168
- draining = !0;
169
- try {
170
- for (; queuedBatches.length > 0;) {
171
- defaultSignal?.throwIfAborted();
172
- let batch = queuedBatches.shift();
173
- if (!batch) continue;
174
- let ids = [...batch.entries()].filter(([, checks]) => checks.some((check) => !check.settled)).map(([id]) => id);
175
- if (ids.length === 0) continue;
176
- let controller = new AbortController(), abortRequest = () => controller.abort(defaultSignal?.reason);
177
- defaultSignal?.addEventListener("abort", abortRequest, { once: !0 }), activeRequest = {
178
- batch,
179
- controller
180
- };
181
- try {
182
- let availability = await client.request({
183
- url: client.getDataUrl("doc", ids.join(",")),
184
- query: { excludeContent: "true" },
185
- signal: controller.signal,
186
- tag: "documents-availability"
187
- }), missingIds = new Set(availability.omitted.filter(({ reason }) => reason === "existence").map(({ id }) => id));
188
- for (let id of ids) for (let check of batch.get(id) ?? []) settleCheck(check, { exists: !missingIds.has(id) });
189
- } catch (error) {
190
- if (controller.signal.aborted && !defaultSignal?.aborted && !hasPendingChecks(batch)) continue;
191
- rejectBatch(batch, error), rejectPending(error);
192
- return;
193
- } finally {
194
- defaultSignal?.removeEventListener("abort", abortRequest), activeRequest = void 0;
195
- }
196
- }
197
- } catch (error) {
198
- rejectPending(error);
199
- } finally {
200
- draining = !1;
201
- }
202
- }
203
- }
204
- return function getDocumentExists(options) {
205
- let signal = options.signal || defaultSignal;
206
- return signal?.aborted ? Promise.reject(signal.reason) : new Promise((resolve, reject) => {
207
- let check = {
208
- reject,
209
- resolve,
210
- settled: !1,
211
- signal
212
- };
213
- signal && (check.onAbort = () => {
214
- settleCheck(check, { error: signal.reason }), activeRequest && !hasPendingChecks(activeRequest.batch) && activeRequest.controller.abort(signal.reason);
215
- }, signal.addEventListener("abort", check.onAbort, { once: !0 }));
216
- let checks = buffer.get(options.id);
217
- checks ? checks.push(check) : buffer.set(options.id, [check]), scheduleFlush();
218
- });
219
- };
220
- }
221
151
  function pathToString(path = []) {
222
152
  return path.reduce((target, segment, i) => {
223
153
  let segmentType = typeof segment;
@@ -633,17 +563,36 @@ const dateValidators = {
633
563
  message: message || i18n.t("validation:object.not-reference")
634
564
  };
635
565
  if (!type) throw Error("`type` was not provided in validation context");
636
- if ("weak" in type && type.weak) return !0;
566
+ let getDocumentType = context.__internal?.getDocumentType, weak = "weak" in type && type.weak;
567
+ if (weak && !getDocumentType) return !0;
637
568
  if (!getDocumentExists) throw Error("`getDocumentExists` was not provided in validation context");
638
- let documentId = document?._id;
639
- return documentId && value._ref == getPublishedId(documentId) || await getDocumentExists({
569
+ let selfReference = document?._id && value._ref === getPublishedId(document._id), exists = selfReference || await getDocumentExists({
640
570
  id: value._ref,
641
571
  signal: context.signal
642
- }) ? !0 : {
572
+ });
573
+ if (!exists && !weak) return {
643
574
  code: validationMarkerCodes.referenceNotPublished,
644
575
  details: { referenceId: value._ref },
645
576
  message: i18n.t("validation:object.reference-not-published", { documentId: value._ref })
646
577
  };
578
+ if (exists && getDocumentType && isReferenceSchemaType(type)) {
579
+ let actualType = selfReference ? document?._type : await getDocumentType(value._ref);
580
+ if (!actualType) throw Error(`Could not read the type of referenced document "${value._ref}"`);
581
+ let allowedTypes = type.to.map((target) => target.name);
582
+ if (!allowedTypes.includes(actualType)) return {
583
+ code: validationMarkerCodes.referenceTargetTypeMismatch,
584
+ details: {
585
+ referenceId: value._ref,
586
+ actualType,
587
+ allowedTypes
588
+ },
589
+ message: i18n.t("validation:object.reference-target-type-mismatch", {
590
+ actualType,
591
+ allowedTypes: allowedTypes.join(", ")
592
+ })
593
+ };
594
+ }
595
+ return !0;
647
596
  },
648
597
  assetRequired: (flag, value, message, { i18n }) => !value || !value.asset || !value.asset._ref ? {
649
598
  __internal_metadata: { name: "assetRequired" },
@@ -759,7 +708,23 @@ async function validateSlugUniqueness(value, context, isUnique) {
759
708
  const slugUniquenessValidator = (value, context) => {
760
709
  let options = context.type?.options;
761
710
  return validateSlugUniqueness(value, context, hasCustomSlugUniqueness(options) ? options.isUnique : defaultIsUnique);
762
- }, DUMMY_ORIGIN = "http://sanity", isRelativeUrl = (url) => /^\.*\//.test(url), emailRegex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, typeValidators = {
711
+ }, DUMMY_ORIGIN = "http://sanity", isRelativeUrl = (url) => /^\.*\//.test(url), SPECIAL_SCHEMES = /* @__PURE__ */ new Set([
712
+ "http:",
713
+ "https:",
714
+ "ws:",
715
+ "wss:",
716
+ "ftp:",
717
+ "file:"
718
+ ]), FORBIDDEN_DOMAIN_CODE_POINT = /[\p{Cc} #/:<>?@[\\\]^|%]/u;
719
+ function hasInvalidDomain(url) {
720
+ if (!SPECIAL_SCHEMES.has(url.protocol) || url.hostname.startsWith("[")) return !1;
721
+ try {
722
+ return FORBIDDEN_DOMAIN_CODE_POINT.test(decodeURIComponent(url.hostname));
723
+ } catch {
724
+ return !0;
725
+ }
726
+ }
727
+ const emailRegex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, typeValidators = {
763
728
  Boolean: booleanValidators,
764
729
  Number: numberValidators,
765
730
  String: {
@@ -794,15 +759,16 @@ const slugUniquenessValidator = (value, context) => {
794
759
  uri: (constraints, value, message, { i18n }) => {
795
760
  let strValue = value || "";
796
761
  if (!strValue) return !0;
797
- let { options } = constraints, { allowCredentials, relativeOnly } = options, allowRelative = options.allowRelative || relativeOnly, url;
762
+ let { options } = constraints, { allowCredentials, relativeOnly } = options, allowRelative = options.allowRelative || relativeOnly, invalidUrl = {
763
+ code: validationMarkerCodes.stringUrlInvalid,
764
+ message: message || i18n.t("validation:string.url.invalid")
765
+ }, url;
798
766
  try {
799
767
  url = allowRelative ? new URL(strValue, DUMMY_ORIGIN) : new URL(strValue);
800
768
  } catch {
801
- return {
802
- code: validationMarkerCodes.stringUrlInvalid,
803
- message: message || i18n.t("validation:string.url.invalid")
804
- };
769
+ return invalidUrl;
805
770
  }
771
+ if (hasInvalidDomain(url)) return invalidUrl;
806
772
  if (relativeOnly && url.origin !== DUMMY_ORIGIN) return {
807
773
  code: validationMarkerCodes.stringUrlNotRelative,
808
774
  message: message || i18n.t("validation:string.url.not-relative")
@@ -861,7 +827,7 @@ const slugUniquenessValidator = (value, context) => {
861
827
  Array: arrayValidators,
862
828
  Object: objectValidators,
863
829
  Date: dateValidators
864
- }, isFieldRef = (constraint) => typeof constraint != "object" || !constraint ? !1 : constraint.type === Rule$2.FIELD_REF, EMPTY_ARRAY = [], fallbackCodeForRule = (flag) => flag === "custom" ? validationMarkerCodes.custom : flag === "media" ? validationMarkerCodes.mediaCustom : flag === "all" ? validationMarkerCodes.ruleAllFailed : flag === "either" ? validationMarkerCodes.ruleEitherFailed : validationMarkerCodes.validationFailed, Rule$2 = class Rule extends Rule$1 {
830
+ }, isFieldRef = (constraint) => typeof constraint != "object" || !constraint ? !1 : constraint.type === Rule.FIELD_REF, EMPTY_ARRAY = [], fallbackCodeForRule = (flag) => flag === "custom" ? validationMarkerCodes.custom : flag === "media" ? validationMarkerCodes.mediaCustom : flag === "all" ? validationMarkerCodes.ruleAllFailed : flag === "either" ? validationMarkerCodes.ruleEitherFailed : validationMarkerCodes.validationFailed, Rule = class Rule extends Rule$2 {
865
831
  static array = (def) => new Rule(def).type("Array");
866
832
  static object = (def) => new Rule(def).type("Object");
867
833
  static string = (def) => new Rule(def).type("String");
@@ -894,7 +860,7 @@ const slugUniquenessValidator = (value, context) => {
894
860
  }
895
861
  let message = isLocalizedMessages(this._message) ? localizeMessage(this._message, context.i18n) : this._message;
896
862
  try {
897
- let validatorContext = curr.flag === "all" || curr.flag === "either" ? {
863
+ let validatorContext = curr.flag === "reference" || curr.flag === "all" || curr.flag === "either" ? {
898
864
  ...context,
899
865
  __internal
900
866
  } : context;
@@ -910,25 +876,111 @@ const slugUniquenessValidator = (value, context) => {
910
876
  }))).flat();
911
877
  }
912
878
  };
913
- /**
914
- * Check if the provided file type should be accepted by the input with accept attribute.
915
- * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input#attr-accept
916
- *
917
- * Inspired by https://github.com/enyo/dropzone (MIT) (c) 2021 Matias Meno
918
- * Based on https://github.com/react-dropzone/attr-accept (MIT) (c) 2015 Andrey Okonetchnikov
919
- *
920
- * @param file - https://developer.mozilla.org/en-US/docs/Web/API/File
921
- * @param acceptedFiles - List of accepted mime types (comma-separated string or array)
922
- * @returns True if file is accepted, false otherwise
923
- * @internal
924
- */
925
- function accepts(file, acceptedFiles) {
926
- if (!file || !acceptedFiles) return !0;
927
- let acceptedFilesArray = Array.isArray(acceptedFiles) ? acceptedFiles : acceptedFiles.split(","), fileName = file.name || "", mimeType = (file.type || "").toLowerCase(), baseMimeType = mimeType.replace(/\/.*$/, "");
928
- return acceptedFilesArray.some((type) => {
929
- let validType = type.trim().toLowerCase();
930
- return validType.charAt(0) === "." ? !fileName || fileName.toLowerCase().endsWith(validType) : validType.endsWith("/*") ? baseMimeType === validType.replace(/\/.*$/, "") : mimeType === validType;
931
- });
879
+ function hasPendingChecks(batch) {
880
+ for (let checks of batch.values()) if (checks.some((check) => !check.settled)) return !0;
881
+ return !1;
882
+ }
883
+ function settleCheck(check, result) {
884
+ check.settled || (check.settled = !0, check.signal && check.onAbort && check.signal.removeEventListener("abort", check.onAbort), "error" in result ? check.reject(result.error) : check.resolve(result.exists));
885
+ }
886
+ function createBatchedGetDocumentExists(client, defaultSignal) {
887
+ let buffer = /* @__PURE__ */ new Map(), queuedBatches = [], bufferTimer, draining = !1, activeRequest, rejectBatch = (batch, reason) => {
888
+ for (let checks of batch.values()) for (let check of checks) settleCheck(check, { error: reason });
889
+ }, rejectPending = (reason) => {
890
+ bufferTimer !== void 0 && clearTimeout(bufferTimer), bufferTimer = void 0, rejectBatch(buffer, reason), buffer = /* @__PURE__ */ new Map();
891
+ for (let batch of queuedBatches.splice(0)) rejectBatch(batch, reason);
892
+ }, flush = () => {
893
+ bufferTimer !== void 0 && clearTimeout(bufferTimer), bufferTimer = void 0, buffer.size !== 0 && (queuedBatches.push(buffer), buffer = /* @__PURE__ */ new Map(), drain());
894
+ }, scheduleFlush = () => {
895
+ buffer.size >= 100 ? flush() : bufferTimer === void 0 && (bufferTimer = setTimeout(flush, 250));
896
+ };
897
+ async function drain() {
898
+ if (!draining) {
899
+ draining = !0;
900
+ try {
901
+ for (; queuedBatches.length > 0;) {
902
+ defaultSignal?.throwIfAborted();
903
+ let batch = queuedBatches.shift();
904
+ if (!batch) continue;
905
+ let ids = [...batch.entries()].filter(([, checks]) => checks.some((check) => !check.settled)).map(([id]) => id);
906
+ if (ids.length === 0) continue;
907
+ let controller = new AbortController(), abortRequest = () => controller.abort(defaultSignal?.reason);
908
+ defaultSignal?.addEventListener("abort", abortRequest, { once: !0 }), activeRequest = {
909
+ batch,
910
+ controller
911
+ };
912
+ try {
913
+ let availability = await client.request({
914
+ url: client.getDataUrl("doc", ids.join(",")),
915
+ query: { excludeContent: "true" },
916
+ signal: controller.signal,
917
+ tag: "documents-availability"
918
+ }), missingIds = new Set(availability.omitted.filter(({ reason }) => reason === "existence").map(({ id }) => id));
919
+ for (let id of ids) for (let check of batch.get(id) ?? []) settleCheck(check, { exists: !missingIds.has(id) });
920
+ } catch (error) {
921
+ if (controller.signal.aborted && !defaultSignal?.aborted && !hasPendingChecks(batch)) continue;
922
+ rejectBatch(batch, error), rejectPending(error);
923
+ return;
924
+ } finally {
925
+ defaultSignal?.removeEventListener("abort", abortRequest), activeRequest = void 0;
926
+ }
927
+ }
928
+ } catch (error) {
929
+ rejectPending(error);
930
+ } finally {
931
+ draining = !1;
932
+ }
933
+ }
934
+ }
935
+ return function getDocumentExists(options) {
936
+ let signal = options.signal || defaultSignal;
937
+ return signal?.aborted ? Promise.reject(signal.reason) : new Promise((resolve, reject) => {
938
+ let check = {
939
+ reject,
940
+ resolve,
941
+ settled: !1,
942
+ signal
943
+ };
944
+ signal && (check.onAbort = () => {
945
+ settleCheck(check, { error: signal.reason }), activeRequest && !hasPendingChecks(activeRequest.batch) && activeRequest.controller.abort(signal.reason);
946
+ }, signal.addEventListener("abort", check.onAbort, { once: !0 }));
947
+ let checks = buffer.get(options.id);
948
+ checks ? checks.push(check) : buffer.set(options.id, [check]), scheduleFlush();
949
+ });
950
+ };
951
+ }
952
+ /** Batches metadata reads and shares each target's result for one validation run. */
953
+ function createBatchedGetDocumentType(getClient, signal) {
954
+ let cache = /* @__PURE__ */ new Map(), pending = /* @__PURE__ */ new Map(), timer;
955
+ async function flush() {
956
+ clearTimeout(timer), timer = void 0;
957
+ let batch = pending;
958
+ pending = /* @__PURE__ */ new Map();
959
+ try {
960
+ signal?.throwIfAborted();
961
+ let documents = await getClient().fetch("*[_id in $ids]{_id, _type}", { ids: [...batch.keys()] }, {
962
+ perspective: "raw",
963
+ useCdn: !1,
964
+ signal,
965
+ tag: "validation.reference-types"
966
+ }), types = new Map(documents.map((document) => [document._id, document._type]));
967
+ for (let [id, check] of batch) check.resolve(types.get(id));
968
+ } catch (error) {
969
+ for (let check of batch.values()) check.reject(error);
970
+ }
971
+ }
972
+ return (id) => {
973
+ if (signal?.aborted) return Promise.reject(signal.reason);
974
+ let cached = cache.get(id);
975
+ if (cached) return cached;
976
+ let result = new Promise((resolve, reject) => {
977
+ pending.set(id, {
978
+ resolve,
979
+ reject
980
+ });
981
+ });
982
+ return cache.set(id, result), pending.size >= 100 ? flush() : timer ??= setTimeout(() => void flush(), 0), result;
983
+ };
932
984
  }
933
985
  const resolvedFileTypes = /* @__PURE__ */ new Map();
934
986
  function isUnknownFileType(fileType) {
@@ -941,10 +993,14 @@ function isUnknownFileType(fileType) {
941
993
  * @internal
942
994
  */
943
995
  function assetMatchesAccept(fileType, accept) {
996
+ let type = fileType.mimeType ?? "";
944
997
  return accepts({
945
- type: fileType.mimeType ?? "",
998
+ type,
946
999
  name: getAssetFilename(fileType)
947
- }, accept);
1000
+ }, accept) || !!(fileType.extension && accepts({
1001
+ type,
1002
+ name: `asset.${fileType.extension}`
1003
+ }, accept));
948
1004
  }
949
1005
  function getAssetFilename(fileType) {
950
1006
  return fileType.originalFilename ? fileType.originalFilename : fileType.extension ? `asset.${fileType.extension}` : void 0;
@@ -1012,7 +1068,7 @@ function extractValueFromListOption(option, typeDef) {
1012
1068
  const isUriSpec = (spec) => spec.flag === "uri";
1013
1069
  function omitLeakedDefaultUri(rules, typeDef) {
1014
1070
  if (!getTypeChain(typeDef).some((type) => type.name === "url")) return rules;
1015
- let defaultUri = new Rule$2(typeDef).uri()._rules.find(isUriSpec)?.constraint, isDefaultUri = (spec) => isUriSpec(spec) && dequal(spec.constraint, defaultUri), isCustomUri = (spec) => isUriSpec(spec) && !dequal(spec.constraint, defaultUri);
1071
+ let defaultUri = new Rule(typeDef).uri()._rules.find(isUriSpec)?.constraint, isDefaultUri = (spec) => isUriSpec(spec) && dequal(spec.constraint, defaultUri), isCustomUri = (spec) => isUriSpec(spec) && !dequal(spec.constraint, defaultUri);
1016
1072
  return rules.some((rule) => rule._rules.some(isCustomUri)) ? rules.map((rule) => {
1017
1073
  if (!rule._rules.some(isDefaultUri)) return rule;
1018
1074
  let cleaned = rule.clone();
@@ -1036,7 +1092,7 @@ function getAcceptOption(typeDef) {
1036
1092
  }
1037
1093
  function inferAssetAcceptRules(typeDef) {
1038
1094
  let accept = getAcceptOption(typeDef), assetType = getTypeChain(typeDef).map((type) => type.name).find(isAcceptedAssetType);
1039
- return accept && assetType ? [new Rule$2(typeDef).custom(markInternalValidator(createAssetAcceptValidator(accept, assetType)), { bypassConcurrencyLimit: !0 }).warning()] : [];
1095
+ return accept && assetType ? [new Rule(typeDef).custom(markInternalValidator(createAssetAcceptValidator(accept, assetType)), { bypassConcurrencyLimit: !0 }).warning()] : [];
1040
1096
  }
1041
1097
  function normalizeAuthoredRules(typeDef, context) {
1042
1098
  let compiled = Array.isArray(typeDef.validation) ? compiledValidations.get(typeDef.validation) : void 0;
@@ -1049,7 +1105,7 @@ function normalizeAuthoredRules(typeDef, context) {
1049
1105
  ...typeDef,
1050
1106
  validation: i
1051
1107
  }, context)), typeDef);
1052
- let initialRule = new Rule$2(typeDef), baseRule = Object.values(getTypeChain(typeDef).reduce((acc, type) => (acc[type.name] = type, acc), {})).reduce(baseRuleReducer, isRuleConstraint(typeDef.jsonType) ? initialRule.type(typeDef.jsonType) : initialRule), options = typeDef.options, list = options && typeof options == "object" && "list" in options ? options.list : void 0;
1108
+ let initialRule = new Rule(typeDef), baseRule = Object.values(getTypeChain(typeDef).reduce((acc, type) => (acc[type.name] = type, acc), {})).reduce(baseRuleReducer, isRuleConstraint(typeDef.jsonType) ? initialRule.type(typeDef.jsonType) : initialRule), options = typeDef.options, list = options && typeof options == "object" && "list" in options ? options.list : void 0;
1053
1109
  return Array.isArray(list) && (baseRule = baseRule.valid(list.map((option) => extractValueFromListOption(option, typeDef)))), validation && typeof validation == "object" ? [validation] : validation && typeof validation == "function" ? normalizeAuthoredRules({
1054
1110
  ...typeDef,
1055
1111
  validation: validation(baseRule, context)
@@ -1179,8 +1235,17 @@ function createPace(scheduling) {
1179
1235
  * @beta
1180
1236
  */
1181
1237
  function withReleaseReferences({ document, getDocumentExists, isUnpublished }) {
1238
+ let resolveReference = createReferenceResolver({
1239
+ document,
1240
+ getDocumentExists,
1241
+ isUnpublished
1242
+ });
1243
+ return async (options) => await resolveReference(options) !== void 0;
1244
+ }
1245
+ /** Resolve the exact published or release document ID used by reference validation. */
1246
+ function createReferenceResolver({ document, getDocumentExists, isUnpublished }) {
1182
1247
  let id = document._id, variant = document._system?.variants?.[0]?._ref ?? document._system?.variant?._ref;
1183
- if (!isVersionId(id) || variant) return getDocumentExists;
1248
+ if (!isVersionId(id) || variant) return async (options) => await getDocumentExists(options) ? options.id : void 0;
1184
1249
  let versionName = getVersionNameFromId(id);
1185
1250
  return async ({ id: referenceId, signal }) => {
1186
1251
  let versionId = getVersionId(referenceId, versionName), [versionExists, publishedExists] = await Promise.all([getDocumentExists({
@@ -1190,10 +1255,10 @@ function withReleaseReferences({ document, getDocumentExists, isUnpublished }) {
1190
1255
  id: referenceId,
1191
1256
  signal
1192
1257
  })]);
1193
- return versionExists ? !await isUnpublished({
1258
+ return versionExists ? await isUnpublished({
1194
1259
  id: versionId,
1195
1260
  signal
1196
- }) : publishedExists;
1261
+ }) ? void 0 : versionId : publishedExists ? referenceId : void 0;
1197
1262
  };
1198
1263
  }
1199
1264
  /**
@@ -1256,7 +1321,7 @@ function resolveTypeForArrayItem(item, candidates) {
1256
1321
  * @beta
1257
1322
  * @deprecated Prefer {@link validateDocument} with `{document, schema, client}` for new code.
1258
1323
  */
1259
- function validateDocumentWithWorkspace({ document, workspace, getClient = workspace.getClient, getDocumentExists, environment = "studio", maxCustomValidationConcurrency, maxFetchConcurrency, currentUser, customValidation, signal }) {
1324
+ function validateDocumentWithWorkspace({ document, workspace, getClient = workspace.getClient, getDocumentExists, environment = "studio", maxCustomValidationConcurrency, maxFetchConcurrency, currentUser, customValidation, signal, validateReferenceTypes = !0 }) {
1260
1325
  return validateDocumentInternal({
1261
1326
  currentUser,
1262
1327
  customValidation,
@@ -1268,7 +1333,8 @@ function validateDocumentWithWorkspace({ document, workspace, getClient = worksp
1268
1333
  maxCustomValidationConcurrency,
1269
1334
  maxFetchConcurrency,
1270
1335
  schema: workspace.schema,
1271
- signal
1336
+ signal,
1337
+ validateReferenceTypes
1272
1338
  });
1273
1339
  }
1274
1340
  /**
@@ -1300,14 +1366,14 @@ function validateDocuments(options) {
1300
1366
  });
1301
1367
  }
1302
1368
  function normalizeValidationOptions(options) {
1303
- let { client, customValidation = !!options.client, getDocumentExists, schema, ...internalOptions } = options;
1369
+ let { client, customValidation = !!options.client, getDocumentExists, i18n, schema, ...internalOptions } = options;
1304
1370
  return {
1305
1371
  ...internalOptions,
1306
1372
  customValidation,
1307
1373
  environment: "cli",
1308
1374
  getClient: client ? ({ apiVersion }) => client.withConfig({ apiVersion }) : throwClientUnavailable,
1309
1375
  getDocumentExists: getDocumentExists || (client ? void 0 : throwClientUnavailable),
1310
- i18n: getFallbackLocaleSource(),
1376
+ i18n: i18n ?? getFallbackLocaleSource(),
1311
1377
  schema
1312
1378
  };
1313
1379
  }
@@ -1344,16 +1410,12 @@ function evaluateDocumentInternal(options) {
1344
1410
  ...sharedOptions
1345
1411
  }).then(([result]) => result);
1346
1412
  }
1347
- function evaluateDocumentsInternal({ documents, schema, getClient, getDocumentExists, i18n = getFallbackLocaleSource(), environment, maxCustomValidationConcurrency, maxFetchConcurrency, currentUser, customValidation = !0, signal }) {
1413
+ function evaluateDocumentsInternal({ documents, schema, getClient, getDocumentExists, i18n = getFallbackLocaleSource(), environment, maxCustomValidationConcurrency, maxFetchConcurrency, currentUser, customValidation = !0, signal, validateReferenceTypes = !0 }) {
1348
1414
  if (signal?.aborted) return Promise.reject(signal.reason);
1349
1415
  if (documents.length === 0) return Promise.resolve([]);
1350
- let limitConcurrency = createClientConcurrencyLimiter(maxFetchConcurrency ?? 25, signal), getConcurrencyLimitedClient = (clientOptions) => limitConcurrency(getClient(clientOptions)), batchedGetDocumentExists = getDocumentExists ? void 0 : createBatchedGetDocumentExists(getClient(DEFAULT_VALIDATION_CLIENT_OPTIONS), signal);
1351
- return Promise.all(documents.map((document) => evaluateDocument({
1352
- document,
1353
- getClient: getConcurrencyLimitedClient,
1354
- i18n,
1355
- schema,
1356
- getDocumentExists: batchedGetDocumentExists ? withReleaseReferences({
1416
+ let limitConcurrency = createClientConcurrencyLimiter(maxFetchConcurrency ?? 25, signal), getConcurrencyLimitedClient = (clientOptions) => limitConcurrency(getClient(clientOptions)), batchedGetDocumentExists = getDocumentExists ? void 0 : createBatchedGetDocumentExists(getClient(DEFAULT_VALIDATION_CLIENT_OPTIONS), signal), batchedGetDocumentType = validateReferenceTypes ? createBatchedGetDocumentType(() => getConcurrencyLimitedClient(DEFAULT_VALIDATION_CLIENT_OPTIONS), signal) : void 0;
1417
+ return Promise.all(documents.map((document) => {
1418
+ let resolveReference = batchedGetDocumentExists ? createReferenceResolver({
1357
1419
  document,
1358
1420
  getDocumentExists: batchedGetDocumentExists,
1359
1421
  isUnpublished: ({ id, signal: checkSignal }) => getConcurrencyLimitedClient(DEFAULT_VALIDATION_CLIENT_OPTIONS).fetch("*[_id == $id][0]._system.delete == true", { id }, {
@@ -1361,14 +1423,28 @@ function evaluateDocumentsInternal({ documents, schema, getClient, getDocumentEx
1361
1423
  signal: checkSignal,
1362
1424
  tag: "validation.release-reference"
1363
1425
  })
1364
- }) : getDocumentExists,
1365
- environment,
1366
- maxCustomValidationConcurrency,
1367
- currentUser,
1368
- customValidation,
1369
- signal,
1370
- pace: createUnpacedPace()
1371
- })));
1426
+ }) : async (options) => await getDocumentExists(options) ? options.id : void 0, resolvedReferences = /* @__PURE__ */ new Map();
1427
+ return evaluateDocument({
1428
+ document,
1429
+ getClient: getConcurrencyLimitedClient,
1430
+ i18n,
1431
+ schema,
1432
+ getDocumentExists: async (options) => {
1433
+ let resolvedId = await resolveReference(options);
1434
+ return batchedGetDocumentType && resolvedId && resolvedReferences.set(options.id, resolvedId), resolvedId !== void 0;
1435
+ },
1436
+ getDocumentType: batchedGetDocumentType ? async (id) => {
1437
+ let resolvedId = resolvedReferences.get(id);
1438
+ return resolvedId ? batchedGetDocumentType(resolvedId) : void 0;
1439
+ } : void 0,
1440
+ environment,
1441
+ maxCustomValidationConcurrency,
1442
+ currentUser,
1443
+ customValidation,
1444
+ signal,
1445
+ pace: createUnpacedPace()
1446
+ });
1447
+ }));
1372
1448
  }
1373
1449
  const customValidationConcurrencyLimiters = /* @__PURE__ */ new WeakMap();
1374
1450
  /**
@@ -1404,7 +1480,7 @@ async function evaluateDocument(options) {
1404
1480
  pace.dispose();
1405
1481
  }
1406
1482
  }
1407
- async function evaluateDocumentWithoutCancellation({ document, getClient, i18n = getFallbackLocaleSource(), schema, getDocumentExists, environment, maxCustomValidationConcurrency, currentUser, customValidation = !0, signal, pace }) {
1483
+ async function evaluateDocumentWithoutCancellation({ document, getClient, i18n = getFallbackLocaleSource(), schema, getDocumentExists, getDocumentType, environment, maxCustomValidationConcurrency, currentUser, customValidation = !0, signal, pace }) {
1408
1484
  try {
1409
1485
  if (typeof document?._type != "string") throw Error("Tried to validate a value without a '_type'");
1410
1486
  let documentType = schema.get(document._type);
@@ -1433,6 +1509,7 @@ async function evaluateDocumentWithoutCancellation({ document, getClient, i18n =
1433
1509
  customValidation,
1434
1510
  signal,
1435
1511
  __internal: {
1512
+ getDocumentType,
1436
1513
  markIncomplete: () => {
1437
1514
  complete = !1;
1438
1515
  },
@@ -1497,19 +1574,19 @@ async function validateItemAsync({ value, type, path = [], parent, customValidat
1497
1574
  value: schemaValue,
1498
1575
  path: schemaPath || [],
1499
1576
  currentUser: restOfContext.currentUser ?? null
1500
- }) : ancestorHiddenValue, hidden = resolveHiddenForType(type, value, parent, path, ancestorHidden), addUnknownFieldsValidator = (rule) => type?.jsonType === "object" && getTypeChain(type).find((t) => [
1577
+ }) : ancestorHiddenValue, hidden = resolveHiddenForType(type, value, parent, path, ancestorHidden), unknownFieldsRule = typeof value == "object" && value && type?.jsonType === "object" && getTypeChain(type).find((t) => [
1501
1578
  "object",
1502
1579
  "document",
1503
1580
  "file",
1504
1581
  "image"
1505
- ].includes(t.name)) && environment !== "studio" ? rule.custom(markInternalValidator(unknownFieldsValidator(type)), { bypassConcurrencyLimit: !0 }).warning() : rule, rules = normalizeValidationRules(type, {
1582
+ ].includes(t.name)) && environment !== "studio" ? new Rule(type).custom(markInternalValidator(unknownFieldsValidator(type)), { bypassConcurrencyLimit: !0 }).warning() : void 0, rules = normalizeValidationRules(type, {
1506
1583
  ...restOfContext,
1507
1584
  hidden,
1508
1585
  environment,
1509
1586
  parent,
1510
1587
  path,
1511
1588
  type
1512
- }), selfChecks = rules.map(addUnknownFieldsValidator).map((rule) => () => validateRule(rule, value, {
1589
+ }), selfChecks = (unknownFieldsRule ? [...rules, unknownFieldsRule] : rules).map((rule) => () => validateRule(rule, value, {
1513
1590
  ...restOfContext,
1514
1591
  environment,
1515
1592
  hidden,
@@ -1536,7 +1613,7 @@ async function validateItemAsync({ value, type, path = [], parent, customValidat
1536
1613
  return normalizeValidationRules({
1537
1614
  ...fieldType,
1538
1615
  validation
1539
- }, fieldContext).map(addUnknownFieldsValidator).map((subRule) => () => validateRule(subRule, nestedValue, {
1616
+ }, fieldContext).map((subRule) => () => validateRule(subRule, nestedValue, {
1540
1617
  ...fieldContext,
1541
1618
  __internal: {
1542
1619
  ...__internal,
@@ -1599,6 +1676,6 @@ function toDocumentValidationMarker(marker) {
1599
1676
  code: validationMarkerCodes.validationFailed
1600
1677
  };
1601
1678
  }
1602
- export { convertToValidationMarker as _, validateDocumentInternal as a, validationLocaleStrings as b, validateDocuments as c, compileValidationRules as d, normalizeValidationRules as f, typeString as g, getTypeChain as h, validateDocument as i, validateItem as l, Rule$2 as m, evaluateDocumentObservable as n, validateDocumentObservable as o, accepts as p, resolveTypeForArrayItem as r, validateDocumentWithWorkspace as s, evaluateDocumentInternal as t, withReleaseReferences as u, pathToString as v, validationMarkerCodes as x, getFallbackLocaleSource as y };
1679
+ export { pathToString as _, validateDocumentInternal as a, validationMarkerCodes as b, validateDocuments as c, compileValidationRules as d, normalizeValidationRules as f, convertToValidationMarker as g, typeString as h, validateDocument as i, validateItem as l, getTypeChain as m, evaluateDocumentObservable as n, validateDocumentObservable as o, Rule as p, resolveTypeForArrayItem as r, validateDocumentWithWorkspace as s, evaluateDocumentInternal as t, withReleaseReferences as u, getFallbackLocaleSource as v, validationLocaleStrings as y };
1603
1680
 
1604
- //# sourceMappingURL=validateDocument-BRt0o35E.js.map
1681
+ //# sourceMappingURL=validateDocument-NMKSm_Yr.js.map