@sanity/validation 6.23.0 → 6.24.0-next.123

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,4 +1,4 @@
1
- import { E as LocaleSource, S as ValidationMarkerCode, T as ValidationScheduling, d as evaluateDocumentInternal, f as evaluateDocumentObservable, g as validateDocumentObservable, h as validateDocumentInternal, n as ValidateDocumentInternalOptions, p as resolveTypeForArrayItem, r as ValidateDocumentObservableOptions, s as ValidateItemOptions, w as ValidationContext, y as validateItem } from "./validateDocument-DESiHtPx.js";
1
+ import { E as LocaleSource, S as ValidationMarkerCode, T as ValidationScheduling, d as evaluateDocumentInternal, f as evaluateDocumentObservable, g as validateDocumentObservable, h as validateDocumentInternal, n as ValidateDocumentInternalOptions, p as resolveTypeForArrayItem, r as ValidateDocumentObservableOptions, s as ValidateItemOptions, w as ValidationContext, y as validateItem } from "./validateDocument-Clpbuo5v.js";
2
2
  import { Path, Rule as Rule$1, RuleClass, Schema, SchemaType, SchemaValidationValue, ValidationContext as ValidationContext$1, ValidationError, ValidationMarker } from "@sanity/types";
3
3
  import { accepts } from "@sanity/util/accepts";
4
4
  export declare function getFallbackLocaleSource(): LocaleSource;
@@ -97,5 +97,4 @@ export declare function getTypeChain(type: SchemaType | undefined, visited?: Set
97
97
  export declare function normalizeValidationRules(typeDef: SchemaType | undefined, context?: ValidationContext$1): Rule$1[];
98
98
  export declare function pathToString(path?: Path | undefined): string;
99
99
  export declare function typeString(obj: unknown): string;
100
- export { type LocaleSource, type ValidateDocumentInternalOptions, type ValidateDocumentObservableOptions, type ValidateItemOptions, type ValidationContext, type ValidationScheduling, accepts, evaluateDocumentInternal, evaluateDocumentObservable, resolveTypeForArrayItem, validateDocumentInternal, validateDocumentObservable, validateItem };
101
- //# sourceMappingURL=_internal.d.ts.map
100
+ export { type LocaleSource, type ValidateDocumentInternalOptions, type ValidateDocumentObservableOptions, type ValidateItemOptions, type ValidationContext, type ValidationScheduling, accepts, evaluateDocumentInternal, evaluateDocumentObservable, resolveTypeForArrayItem, validateDocumentInternal, validateDocumentObservable, validateItem };
package/lib/_internal.js CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as pathToString, a as validateDocumentInternal, d as compileValidationRules, f as normalizeValidationRules, g as convertToValidationMarker, h as typeString, l as validateItem, m as getTypeChain, n as evaluateDocumentObservable, o as validateDocumentObservable, p as Rule, r as resolveTypeForArrayItem, t as evaluateDocumentInternal, v as getFallbackLocaleSource, y as validationLocaleStrings } from "./validateDocument-DZEYmQ4p.js";
1
+ import { _ as pathToString, a as validateDocumentInternal, d as compileValidationRules, f as normalizeValidationRules, g as convertToValidationMarker, h as typeString, l as validateItem, m as getTypeChain, n as evaluateDocumentObservable, o as validateDocumentObservable, p as Rule, r as resolveTypeForArrayItem, t as evaluateDocumentInternal, v as getFallbackLocaleSource, y as validationLocaleStrings } from "./validateDocument-NMKSm_Yr.js";
2
2
  import { accepts } from "@sanity/util/accepts";
3
3
  function inferFromSchemaType(typeDef) {
4
4
  return traverse(typeDef, /* @__PURE__ */ new Set()), typeDef;
@@ -1 +1 @@
1
- {"version":3,"file":"_internal.js","names":[],"sources":["../src/inferFromSchemaType.ts","../src/inferFromSchema.ts"],"sourcesContent":["import {type Schema, type SchemaType, type SchemaValidationValue} from '@sanity/types'\n\nimport {compileValidationRules} from './util/normalizeValidationRules'\n\n// NOTE: this overload is for TS API compatibility with a previous implementation\nexport function inferFromSchemaType(\n typeDef: SchemaType,\n // these are intentionally unused\n _schema: Schema,\n _visited?: Set<SchemaType>,\n): SchemaType\n// note: this seemingly redundant overload is required\nexport function inferFromSchemaType(typeDef: SchemaType): SchemaType\nexport function inferFromSchemaType(typeDef: SchemaType): SchemaType {\n traverse(typeDef, new Set())\n return typeDef\n}\n\nfunction traverse(typeDef: SchemaType, visited: Set<SchemaType>) {\n if (visited.has(typeDef)) {\n return\n }\n\n visited.add(typeDef)\n\n const usesValidationContext = hasValidationContext(typeDef.validation)\n\n // Only normalize validation at schema-compile time when it doesn't rely on runtime context.\n // Context-aware validation functions must be evaluated during validation, where context exists.\n if (!usesValidationContext) {\n typeDef.validation = compileValidationRules(typeDef)\n }\n\n if ('fields' in typeDef) {\n for (const field of typeDef.fields) {\n traverse(field.type, visited)\n }\n }\n\n if ('of' in typeDef) {\n for (const candidate of typeDef.of) {\n traverse(candidate, visited)\n }\n }\n\n // @ts-expect-error TODO (eventually): `annotations` does not exist on the SchemaType yet\n if (typeDef.annotations) {\n // @ts-expect-error TODO (eventually): `annotations` does not exist on the SchemaType yet\n for (const annotation of typeDef.annotations) {\n traverse(annotation, visited)\n }\n }\n}\n\n/**\n * Checks if a validation function may use the context parameter.\n *\n * Functions with 2+ parameters like `(rule, context) => ...` need runtime context\n * (e.g., `context.hidden`, `context.document`) and cannot be pre-evaluated at schema compile time.\n *\n * Simple functions with only a rule parameter can be normalized immediately.\n * Unrecognized signatures are deferred because their arity may hide context usage.\n *\n * @internal\n */\nexport function hasValidationContext(validation: SchemaValidationValue | undefined): boolean {\n if (!validation) return false\n if (Array.isArray(validation)) {\n return validation.some(hasValidationContext)\n }\n if (typeof validation !== 'function') return false\n\n // Check declared parameter count first (most common case)\n if (validation.length >= 2) return true\n\n // Default and rest parameters do not contribute to Function.length. Only compile\n // recognizable zero/one-parameter signatures; wrappers and unknown forms stay at runtime.\n const signature = Function.prototype.toString.call(validation)\n if (/\\barguments\\b|\\[native code\\]/.test(signature)) return true\n\n const simpleArrow = /^\\s*(?:[\\w$]+|\\(\\s*(?:[\\w$]+\\s*)?\\))\\s*=>/\n const simpleFunction = /^\\s*(?:function(?:\\s+[\\w$]+)?|[\\w$]+)\\s*\\(\\s*(?:[\\w$]+\\s*)?\\)\\s*\\{/\n return !simpleArrow.test(signature) && !simpleFunction.test(signature)\n}\n","import {type Schema} from '@sanity/types'\n\nimport {inferFromSchemaType} from './inferFromSchemaType'\n\n// Note: Mutates schema. Refactor when @sanity/schema supports middlewares\nexport function inferFromSchema(schema: Schema): Schema {\n const typeNames = schema.getLocalTypeNames()\n\n typeNames.forEach((typeName) => {\n const schemaType = schema.get(typeName)\n\n if (schemaType) {\n inferFromSchemaType(schemaType)\n }\n })\n\n return schema\n}\n"],"mappings":";;AAaA,SAAgB,oBAAoB,SAAiC;CAEnE,OADA,SAAS,yBAAS,IAAI,IAAI,CAAC,GACpB;AACT;AAEA,SAAS,SAAS,SAAqB,SAA0B;CAC/D,IAAI,SAAQ,IAAI,OAAO,GAIvB;EAUA,IAVA,QAAQ,IAAI,OAAO,GAEW,qBAAqB,QAAQ,UAIlC,MACvB,QAAQ,aAAa,uBAAuB,OAAO,IAGjD,YAAY,SACd,KAAK,IAAM,SAAS,QAAQ,QAC1B,SAAS,MAAM,MAAM,OAAO;EAIhC,IAAI,QAAQ,SACV,KAAK,IAAM,aAAa,QAAQ,IAC9B,SAAS,WAAW,OAAO;EAK/B,IAAI,QAAQ,aAEV,KAAK,IAAM,cAAc,QAAQ,aAC/B,SAAS,YAAY,OAAO;CA1Bb;AA6BrB;;;;;;;;;;;;AAaA,SAAgB,qBAAqB,YAAwD;CAC3F,IAAI,CAAC,YAAY,OAAO;CACxB,IAAI,MAAM,QAAQ,UAAU,GAC1B,OAAO,WAAW,KAAK,oBAAoB;CAE7C,IAAI,OAAO,cAAe,YAAY,OAAO;CAG7C,IAAI,WAAW,UAAU,GAAG,OAAO;CAInC,IAAM,YAAY,SAAS,UAAU,SAAS,KAAK,UAAU;CAK7D,OAJI,gCAAgC,KAAK,SAAS,IAAU,KAIrD,CAAC,4CAAY,KAAK,SAAS,KAAK,CAAC,qEAAe,KAAK,SAAS;AACvE;AC9EA,SAAgB,gBAAgB,QAAwB;CAWtD,OARA,OAFyB,kBAEjB,CAAC,CAAC,SAAS,aAAa;EAC9B,IAAM,aAAa,OAAO,IAAI,QAAQ;EAEtC,AAAI,cACF,oBAAoB,UAAU;CAElC,CAAC,GAEM;AACT"}
1
+ {"version":3,"file":"_internal.js","names":[],"sources":["../src/inferFromSchemaType.ts","../src/inferFromSchema.ts"],"sourcesContent":["import {type Schema, type SchemaType, type SchemaValidationValue} from '@sanity/types'\n\nimport {compileValidationRules} from './util/normalizeValidationRules'\n\n// NOTE: this overload is for TS API compatibility with a previous implementation\nexport function inferFromSchemaType(\n typeDef: SchemaType,\n // these are intentionally unused\n _schema: Schema,\n _visited?: Set<SchemaType>,\n): SchemaType\n// note: this seemingly redundant overload is required\nexport function inferFromSchemaType(typeDef: SchemaType): SchemaType\nexport function inferFromSchemaType(typeDef: SchemaType): SchemaType {\n traverse(typeDef, new Set())\n return typeDef\n}\n\nfunction traverse(typeDef: SchemaType, visited: Set<SchemaType>) {\n if (visited.has(typeDef)) {\n return\n }\n\n visited.add(typeDef)\n\n const usesValidationContext = hasValidationContext(typeDef.validation)\n\n // Only normalize validation at schema-compile time when it doesn't rely on runtime context.\n // Context-aware validation functions must be evaluated during validation, where context exists.\n if (!usesValidationContext) {\n typeDef.validation = compileValidationRules(typeDef)\n }\n\n if ('fields' in typeDef) {\n for (const field of typeDef.fields) {\n traverse(field.type, visited)\n }\n }\n\n if ('of' in typeDef) {\n for (const candidate of typeDef.of) {\n traverse(candidate, visited)\n }\n }\n\n // @ts-expect-error TODO (eventually): `annotations` does not exist on the SchemaType yet\n if (typeDef.annotations) {\n // @ts-expect-error TODO (eventually): `annotations` does not exist on the SchemaType yet\n for (const annotation of typeDef.annotations) {\n traverse(annotation, visited)\n }\n }\n}\n\n/**\n * Checks if a validation function may use the context parameter.\n *\n * Functions with 2+ parameters like `(rule, context) => ...` need runtime context\n * (e.g., `context.hidden`, `context.document`) and cannot be pre-evaluated at schema compile time.\n *\n * Simple functions with only a rule parameter can be normalized immediately.\n * Unrecognized signatures are deferred because their arity may hide context usage.\n *\n * @internal\n */\nexport function hasValidationContext(validation: SchemaValidationValue | undefined): boolean {\n if (!validation) return false\n if (Array.isArray(validation)) {\n return validation.some(hasValidationContext)\n }\n if (typeof validation !== 'function') return false\n\n // Check declared parameter count first (most common case)\n if (validation.length >= 2) return true\n\n // Default and rest parameters do not contribute to Function.length. Only compile\n // recognizable zero/one-parameter signatures; wrappers and unknown forms stay at runtime.\n const signature = Function.prototype.toString.call(validation)\n if (/\\barguments\\b|\\[native code\\]/.test(signature)) return true\n\n const simpleArrow = /^\\s*(?:[\\w$]+|\\(\\s*(?:[\\w$]+\\s*)?\\))\\s*=>/\n const simpleFunction = /^\\s*(?:function(?:\\s+[\\w$]+)?|[\\w$]+)\\s*\\(\\s*(?:[\\w$]+\\s*)?\\)\\s*\\{/\n return !simpleArrow.test(signature) && !simpleFunction.test(signature)\n}\n","import {type Schema} from '@sanity/types'\n\nimport {inferFromSchemaType} from './inferFromSchemaType'\n\n// Note: Mutates schema. Refactor when @sanity/schema supports middlewares\nexport function inferFromSchema(schema: Schema): Schema {\n const typeNames = schema.getLocalTypeNames()\n\n typeNames.forEach((typeName) => {\n const schemaType = schema.get(typeName)\n\n if (schemaType) {\n inferFromSchemaType(schemaType)\n }\n })\n\n return schema\n}\n"],"mappings":";;AAaA,SAAgB,oBAAoB,SAAiC;CAEnE,OADA,SAAS,yBAAS,IAAI,IAAI,CAAC,GACpB;AACT;AAEA,SAAS,SAAS,SAAqB,SAA0B;CAC/D,IAAI,SAAQ,IAAI,OAAO,GAIvB;EAUA,IAVA,QAAQ,IAAI,OAAO,GAEW,qBAAqB,QAAQ,UAIlC,MACvB,QAAQ,aAAa,uBAAuB,OAAO,IAGjD,YAAY,SACd,KAAK,IAAM,SAAS,QAAQ,QAC1B,SAAS,MAAM,MAAM,OAAO;EAIhC,IAAI,QAAQ,SACV,KAAK,IAAM,aAAa,QAAQ,IAC9B,SAAS,WAAW,OAAO;EAK/B,IAAI,QAAQ,aAEV,KAAK,IAAM,cAAc,QAAQ,aAC/B,SAAS,YAAY,OAAO;CA1Bb;AA6BrB;;;;;;;;;;;;AAaA,SAAgB,qBAAqB,YAAwD;CAC3F,IAAI,CAAC,YAAY,OAAO;CACxB,IAAI,MAAM,QAAQ,UAAU,GAC1B,OAAO,WAAW,KAAK,oBAAoB;CAE7C,IAAI,OAAO,cAAe,YAAY,OAAO;CAG7C,IAAI,WAAW,UAAU,GAAG,OAAO;CAInC,IAAM,YAAY,SAAS,UAAU,SAAS,KAAK,UAAU;CAK7D,OAJI,gCAAgC,KAAK,SAAS,IAAU,KAIrD,CAAC,4CAAY,KAAK,SAAS,KAAK,CAAC,qEAAe,KAAK,SAAS;AACvE;AC9EA,SAAgB,gBAAgB,QAAwB;CAWtD,OAVkB,OAAO,kBAEjB,CAAC,CAAC,SAAS,aAAa;EAC9B,IAAM,aAAa,OAAO,IAAI,QAAQ;EAElC,cACF,oBAAoB,UAAU;CAElC,CAAC,GAEM;AACT"}
package/lib/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { C as validationMarkerCodes, D as ValidationLocaleSource, S as ValidationMarkerCode, _ as validateDocumentWithWorkspace, a as ValidateDocumentWorkspaceOptions, b as BuiltInValidationMarkerCode, c as ValidationClient, i as ValidateDocumentOptions, l as ValidationSchema, m as validateDocument, o as ValidateDocumentsOptions, t as DocumentValidationResult, u as ValidationSource, v as validateDocuments, x as DocumentValidationMarker } from "./validateDocument-DESiHtPx.js";
1
+ import { C as validationMarkerCodes, D as ValidationLocaleSource, S as ValidationMarkerCode, _ as validateDocumentWithWorkspace, a as ValidateDocumentWorkspaceOptions, b as BuiltInValidationMarkerCode, c as ValidationClient, i as ValidateDocumentOptions, l as ValidationSchema, m as validateDocument, o as ValidateDocumentsOptions, t as DocumentValidationResult, u as ValidationSource, v as validateDocuments, x as DocumentValidationMarker } from "./validateDocument-Clpbuo5v.js";
2
2
  import { SanityDocument } from "@sanity/types";
3
3
  type DocumentCheck = (options: {
4
4
  id: string;
@@ -21,5 +21,4 @@ interface ReleaseReferenceOptions {
21
21
  * @beta
22
22
  */
23
23
  export declare function withReleaseReferences({ document, getDocumentExists, isUnpublished }: ReleaseReferenceOptions): DocumentCheck;
24
- export { type BuiltInValidationMarkerCode, type DocumentValidationMarker, type DocumentValidationResult, type ReleaseReferenceOptions, type ValidateDocumentOptions, type ValidateDocumentWorkspaceOptions, type ValidateDocumentsOptions, type ValidationClient, type ValidationLocaleSource, type ValidationMarkerCode, type ValidationSchema, type ValidationSource, validateDocument, validateDocumentWithWorkspace, validateDocuments, validationMarkerCodes };
25
- //# sourceMappingURL=index.d.ts.map
24
+ export { type BuiltInValidationMarkerCode, type DocumentValidationMarker, type DocumentValidationResult, type ReleaseReferenceOptions, type ValidateDocumentOptions, type ValidateDocumentWorkspaceOptions, type ValidateDocumentsOptions, type ValidationClient, type ValidationLocaleSource, type ValidationMarkerCode, type ValidationSchema, type ValidationSource, validateDocument, validateDocumentWithWorkspace, validateDocuments, validationMarkerCodes };
package/lib/index.js CHANGED
@@ -1 +1 @@
1
- export { i as validateDocument, s as validateDocumentWithWorkspace, c as validateDocuments, b as validationMarkerCodes, u as withReleaseReferences } from "./validateDocument-DZEYmQ4p.js";
1
+ export { i as validateDocument, s as validateDocumentWithWorkspace, c as validateDocuments, b as validationMarkerCodes, u as withReleaseReferences } from "./validateDocument-NMKSm_Yr.js";
@@ -65,7 +65,7 @@ declare module '@sanity/types' {
65
65
  i18n: LocaleSource;
66
66
  }
67
67
  }
68
- interface InternalValidationContext extends ValidationContext {
68
+ interface InternalValidationContext extends ValidationContext$1 {
69
69
  __internal?: {
70
70
  getDocumentType?: (id: string) => Promise<string | undefined>;
71
71
  customValidation?: boolean;
@@ -354,7 +354,7 @@ declare function evaluateDocumentInternal(options: ValidateDocumentInternalOptio
354
354
  /**
355
355
  * @internal
356
356
  */
357
- interface ValidateDocumentObservableOptions extends Pick<ValidationContext$1, 'getDocumentExists' | 'i18n' | 'signal' | 'currentUser'> {
357
+ interface ValidateDocumentObservableOptions extends Pick<ValidationContext, 'getDocumentExists' | 'i18n' | 'signal' | 'currentUser'> {
358
358
  /** Lookup for resolved target types. Omit to disable type checks. */
359
359
  getDocumentType?: (id: string) => Promise<string | undefined>;
360
360
  getClient: (options: {
@@ -398,7 +398,6 @@ type ValidateItemOptions = {
398
398
  /** See {@link ValidateDocumentObservableOptions.scheduling}. */
399
399
  scheduling?: BehaviorSubject<ValidationScheduling>;
400
400
  __internal?: InternalValidationContext['__internal'];
401
- } & Pick<ValidationContext$1, 'currentUser'> & ExplicitUndefined<Omit<ValidationContext$1, 'hidden' | 'signal' | 'currentUser'>>;
401
+ } & Pick<ValidationContext, 'currentUser'> & ExplicitUndefined<Omit<ValidationContext, 'hidden' | 'signal' | 'currentUser'>>;
402
402
  declare function validateItem(opts: ValidateItemOptions): Promise<ValidationMarker[]>;
403
- export { validationMarkerCodes as C, ValidationLocaleSource as D, LocaleSource as E, ValidationMarkerCode as S, ValidationScheduling as T, validateDocumentWithWorkspace as _, ValidateDocumentWorkspaceOptions as a, BuiltInValidationMarkerCode as b, ValidationClient as c, evaluateDocumentInternal as d, evaluateDocumentObservable as f, validateDocumentObservable as g, validateDocumentInternal as h, ValidateDocumentOptions as i, ValidationSchema as l, validateDocument as m, ValidateDocumentInternalOptions as n, ValidateDocumentsOptions as o, resolveTypeForArrayItem as p, ValidateDocumentObservableOptions as r, ValidateItemOptions as s, DocumentValidationResult as t, ValidationSource as u, validateDocuments as v, ValidationContext$1 as w, DocumentValidationMarker as x, validateItem as y };
404
- //# sourceMappingURL=validateDocument-DESiHtPx.d.ts.map
403
+ export { validationMarkerCodes as C, ValidationLocaleSource as D, LocaleSource as E, ValidationMarkerCode as S, ValidationScheduling as T, validateDocumentWithWorkspace as _, ValidateDocumentWorkspaceOptions as a, BuiltInValidationMarkerCode as b, ValidationClient as c, evaluateDocumentInternal as d, evaluateDocumentObservable as f, validateDocumentObservable as g, validateDocumentInternal as h, ValidateDocumentOptions as i, ValidationSchema as l, validateDocument as m, ValidateDocumentInternalOptions as n, ValidateDocumentsOptions as o, resolveTypeForArrayItem as p, ValidateDocumentObservableOptions as r, ValidateItemOptions as s, DocumentValidationResult as t, ValidationSource as u, validateDocuments as v, ValidationContext as w, DocumentValidationMarker as x, validateItem as y };
@@ -7,7 +7,7 @@ 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";
@@ -148,112 +148,6 @@ function resolveConditionalProperty(property, context) {
148
148
  path
149
149
  }) === !0;
150
150
  }
151
- function hasPendingChecks(batch) {
152
- for (let checks of batch.values()) if (checks.some((check) => !check.settled)) return !0;
153
- return !1;
154
- }
155
- function settleCheck(check, result) {
156
- 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));
157
- }
158
- function createBatchedGetDocumentExists(client, defaultSignal) {
159
- let buffer = /* @__PURE__ */ new Map(), queuedBatches = [], bufferTimer, draining = !1, activeRequest, rejectBatch = (batch, reason) => {
160
- for (let checks of batch.values()) for (let check of checks) settleCheck(check, { error: reason });
161
- }, rejectPending = (reason) => {
162
- bufferTimer !== void 0 && clearTimeout(bufferTimer), bufferTimer = void 0, rejectBatch(buffer, reason), buffer = /* @__PURE__ */ new Map();
163
- for (let batch of queuedBatches.splice(0)) rejectBatch(batch, reason);
164
- }, flush = () => {
165
- bufferTimer !== void 0 && clearTimeout(bufferTimer), bufferTimer = void 0, buffer.size !== 0 && (queuedBatches.push(buffer), buffer = /* @__PURE__ */ new Map(), drain());
166
- }, scheduleFlush = () => {
167
- buffer.size >= 100 ? flush() : bufferTimer === void 0 && (bufferTimer = setTimeout(flush, 250));
168
- };
169
- async function drain() {
170
- if (!draining) {
171
- draining = !0;
172
- try {
173
- for (; queuedBatches.length > 0;) {
174
- defaultSignal?.throwIfAborted();
175
- let batch = queuedBatches.shift();
176
- if (!batch) continue;
177
- let ids = [...batch.entries()].filter(([, checks]) => checks.some((check) => !check.settled)).map(([id]) => id);
178
- if (ids.length === 0) continue;
179
- let controller = new AbortController(), abortRequest = () => controller.abort(defaultSignal?.reason);
180
- defaultSignal?.addEventListener("abort", abortRequest, { once: !0 }), activeRequest = {
181
- batch,
182
- controller
183
- };
184
- try {
185
- let availability = await client.request({
186
- url: client.getDataUrl("doc", ids.join(",")),
187
- query: { excludeContent: "true" },
188
- signal: controller.signal,
189
- tag: "documents-availability"
190
- }), missingIds = new Set(availability.omitted.filter(({ reason }) => reason === "existence").map(({ id }) => id));
191
- for (let id of ids) for (let check of batch.get(id) ?? []) settleCheck(check, { exists: !missingIds.has(id) });
192
- } catch (error) {
193
- if (controller.signal.aborted && !defaultSignal?.aborted && !hasPendingChecks(batch)) continue;
194
- rejectBatch(batch, error), rejectPending(error);
195
- return;
196
- } finally {
197
- defaultSignal?.removeEventListener("abort", abortRequest), activeRequest = void 0;
198
- }
199
- }
200
- } catch (error) {
201
- rejectPending(error);
202
- } finally {
203
- draining = !1;
204
- }
205
- }
206
- }
207
- return function getDocumentExists(options) {
208
- let signal = options.signal || defaultSignal;
209
- return signal?.aborted ? Promise.reject(signal.reason) : new Promise((resolve, reject) => {
210
- let check = {
211
- reject,
212
- resolve,
213
- settled: !1,
214
- signal
215
- };
216
- signal && (check.onAbort = () => {
217
- settleCheck(check, { error: signal.reason }), activeRequest && !hasPendingChecks(activeRequest.batch) && activeRequest.controller.abort(signal.reason);
218
- }, signal.addEventListener("abort", check.onAbort, { once: !0 }));
219
- let checks = buffer.get(options.id);
220
- checks ? checks.push(check) : buffer.set(options.id, [check]), scheduleFlush();
221
- });
222
- };
223
- }
224
- /** Batches metadata reads and shares each target's result for one validation run. */
225
- function createBatchedGetDocumentType(getClient, signal) {
226
- let cache = /* @__PURE__ */ new Map(), pending = /* @__PURE__ */ new Map(), timer;
227
- async function flush() {
228
- clearTimeout(timer), timer = void 0;
229
- let batch = pending;
230
- pending = /* @__PURE__ */ new Map();
231
- try {
232
- signal?.throwIfAborted();
233
- let documents = await getClient().fetch("*[_id in $ids]{_id, _type}", { ids: [...batch.keys()] }, {
234
- perspective: "raw",
235
- useCdn: !1,
236
- signal,
237
- tag: "validation.reference-types"
238
- }), types = new Map(documents.map((document) => [document._id, document._type]));
239
- for (let [id, check] of batch) check.resolve(types.get(id));
240
- } catch (error) {
241
- for (let check of batch.values()) check.reject(error);
242
- }
243
- }
244
- return (id) => {
245
- if (signal?.aborted) return Promise.reject(signal.reason);
246
- let cached = cache.get(id);
247
- if (cached) return cached;
248
- let result = new Promise((resolve, reject) => {
249
- pending.set(id, {
250
- resolve,
251
- reject
252
- });
253
- });
254
- return cache.set(id, result), pending.size >= 100 ? flush() : timer ??= setTimeout(() => void flush(), 0), result;
255
- };
256
- }
257
151
  function pathToString(path = []) {
258
152
  return path.reduce((target, segment, i) => {
259
153
  let segmentType = typeof segment;
@@ -814,7 +708,23 @@ async function validateSlugUniqueness(value, context, isUnique) {
814
708
  const slugUniquenessValidator = (value, context) => {
815
709
  let options = context.type?.options;
816
710
  return validateSlugUniqueness(value, context, hasCustomSlugUniqueness(options) ? options.isUnique : defaultIsUnique);
817
- }, 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 = {
818
728
  Boolean: booleanValidators,
819
729
  Number: numberValidators,
820
730
  String: {
@@ -849,15 +759,16 @@ const slugUniquenessValidator = (value, context) => {
849
759
  uri: (constraints, value, message, { i18n }) => {
850
760
  let strValue = value || "";
851
761
  if (!strValue) return !0;
852
- 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;
853
766
  try {
854
767
  url = allowRelative ? new URL(strValue, DUMMY_ORIGIN) : new URL(strValue);
855
768
  } catch {
856
- return {
857
- code: validationMarkerCodes.stringUrlInvalid,
858
- message: message || i18n.t("validation:string.url.invalid")
859
- };
769
+ return invalidUrl;
860
770
  }
771
+ if (hasInvalidDomain(url)) return invalidUrl;
861
772
  if (relativeOnly && url.origin !== DUMMY_ORIGIN) return {
862
773
  code: validationMarkerCodes.stringUrlNotRelative,
863
774
  message: message || i18n.t("validation:string.url.not-relative")
@@ -916,7 +827,7 @@ const slugUniquenessValidator = (value, context) => {
916
827
  Array: arrayValidators,
917
828
  Object: objectValidators,
918
829
  Date: dateValidators
919
- }, 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 {
920
831
  static array = (def) => new Rule(def).type("Array");
921
832
  static object = (def) => new Rule(def).type("Object");
922
833
  static string = (def) => new Rule(def).type("String");
@@ -964,7 +875,114 @@ const slugUniquenessValidator = (value, context) => {
964
875
  }
965
876
  }))).flat();
966
877
  }
967
- }, resolvedFileTypes = /* @__PURE__ */ new Map();
878
+ };
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
+ };
984
+ }
985
+ const resolvedFileTypes = /* @__PURE__ */ new Map();
968
986
  function isUnknownFileType(fileType) {
969
987
  return [fileType.mimeType, fileType.extension].every((value) => (value ?? "") === "");
970
988
  }
@@ -975,10 +993,14 @@ function isUnknownFileType(fileType) {
975
993
  * @internal
976
994
  */
977
995
  function assetMatchesAccept(fileType, accept) {
996
+ let type = fileType.mimeType ?? "";
978
997
  return accepts({
979
- type: fileType.mimeType ?? "",
998
+ type,
980
999
  name: getAssetFilename(fileType)
981
- }, accept);
1000
+ }, accept) || !!(fileType.extension && accepts({
1001
+ type,
1002
+ name: `asset.${fileType.extension}`
1003
+ }, accept));
982
1004
  }
983
1005
  function getAssetFilename(fileType) {
984
1006
  return fileType.originalFilename ? fileType.originalFilename : fileType.extension ? `asset.${fileType.extension}` : void 0;
@@ -1046,7 +1068,7 @@ function extractValueFromListOption(option, typeDef) {
1046
1068
  const isUriSpec = (spec) => spec.flag === "uri";
1047
1069
  function omitLeakedDefaultUri(rules, typeDef) {
1048
1070
  if (!getTypeChain(typeDef).some((type) => type.name === "url")) return rules;
1049
- 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);
1050
1072
  return rules.some((rule) => rule._rules.some(isCustomUri)) ? rules.map((rule) => {
1051
1073
  if (!rule._rules.some(isDefaultUri)) return rule;
1052
1074
  let cleaned = rule.clone();
@@ -1070,7 +1092,7 @@ function getAcceptOption(typeDef) {
1070
1092
  }
1071
1093
  function inferAssetAcceptRules(typeDef) {
1072
1094
  let accept = getAcceptOption(typeDef), assetType = getTypeChain(typeDef).map((type) => type.name).find(isAcceptedAssetType);
1073
- 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()] : [];
1074
1096
  }
1075
1097
  function normalizeAuthoredRules(typeDef, context) {
1076
1098
  let compiled = Array.isArray(typeDef.validation) ? compiledValidations.get(typeDef.validation) : void 0;
@@ -1083,7 +1105,7 @@ function normalizeAuthoredRules(typeDef, context) {
1083
1105
  ...typeDef,
1084
1106
  validation: i
1085
1107
  }, context)), typeDef);
1086
- 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;
1087
1109
  return Array.isArray(list) && (baseRule = baseRule.valid(list.map((option) => extractValueFromListOption(option, typeDef)))), validation && typeof validation == "object" ? [validation] : validation && typeof validation == "function" ? normalizeAuthoredRules({
1088
1110
  ...typeDef,
1089
1111
  validation: validation(baseRule, context)
@@ -1552,19 +1574,19 @@ async function validateItemAsync({ value, type, path = [], parent, customValidat
1552
1574
  value: schemaValue,
1553
1575
  path: schemaPath || [],
1554
1576
  currentUser: restOfContext.currentUser ?? null
1555
- }) : 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) => [
1556
1578
  "object",
1557
1579
  "document",
1558
1580
  "file",
1559
1581
  "image"
1560
- ].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, {
1561
1583
  ...restOfContext,
1562
1584
  hidden,
1563
1585
  environment,
1564
1586
  parent,
1565
1587
  path,
1566
1588
  type
1567
- }), selfChecks = rules.map(addUnknownFieldsValidator).map((rule) => () => validateRule(rule, value, {
1589
+ }), selfChecks = (unknownFieldsRule ? [...rules, unknownFieldsRule] : rules).map((rule) => () => validateRule(rule, value, {
1568
1590
  ...restOfContext,
1569
1591
  environment,
1570
1592
  hidden,
@@ -1591,7 +1613,7 @@ async function validateItemAsync({ value, type, path = [], parent, customValidat
1591
1613
  return normalizeValidationRules({
1592
1614
  ...fieldType,
1593
1615
  validation
1594
- }, fieldContext).map(addUnknownFieldsValidator).map((subRule) => () => validateRule(subRule, nestedValue, {
1616
+ }, fieldContext).map((subRule) => () => validateRule(subRule, nestedValue, {
1595
1617
  ...fieldContext,
1596
1618
  __internal: {
1597
1619
  ...__internal,
@@ -1654,6 +1676,6 @@ function toDocumentValidationMarker(marker) {
1654
1676
  code: validationMarkerCodes.validationFailed
1655
1677
  };
1656
1678
  }
1657
- 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$2 as p, resolveTypeForArrayItem as r, validateDocumentWithWorkspace as s, evaluateDocumentInternal as t, withReleaseReferences as u, getFallbackLocaleSource as v, validationLocaleStrings 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 };
1658
1680
 
1659
- //# sourceMappingURL=validateDocument-DZEYmQ4p.js.map
1681
+ //# sourceMappingURL=validateDocument-NMKSm_Yr.js.map