@sanity/validation 6.23.0-next.7 → 6.24.0-next.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -0
- package/lib/_internal.d.ts +4 -18
- package/lib/_internal.js +2 -1
- package/lib/_internal.js.map +1 -1
- package/lib/index.d.ts +2 -2
- package/lib/index.js +1 -1
- package/lib/{validateDocument-BRt0o35E.js → validateDocument-B0K7YlIj.js} +138 -62
- package/lib/validateDocument-B0K7YlIj.js.map +1 -0
- package/lib/{validateDocument-CnUrz4db.d.ts → validateDocument-DESiHtPx.d.ts} +35 -5
- package/package.json +5 -5
- package/lib/validateDocument-BRt0o35E.js.map +0 -1
package/README.md
CHANGED
|
@@ -24,6 +24,7 @@ if (!complete) {
|
|
|
24
24
|
- `status` is deprecated; use `complete` and inspect marker levels and codes. It treats any marker as `failed`.
|
|
25
25
|
- Built-in codes: `validationMarkerCodes`. Custom validators can return namespaced codes such as `custom.seo-title`.
|
|
26
26
|
- Omit `client` for local checks without custom callbacks or network checks. Skipped checks make `complete` false. Use `customValidation: false` to skip custom callbacks while keeping network checks.
|
|
27
|
+
- Pass `i18n: workspace.i18n` to `validateDocument`/`validateDocuments` to preserve the workspace's locale and translation resources, including those used by custom validators through `context.i18n`.
|
|
27
28
|
- Precompiled rules retain their original package version's behavior; recompile with the current version for current callback-skipping and concurrency semantics.
|
|
28
29
|
|
|
29
30
|
## Batch validation
|
|
@@ -37,6 +38,12 @@ const results = await validateDocuments({documents, schema, client, maxFetchConc
|
|
|
37
38
|
|
|
38
39
|
`maxFetchConcurrency` defaults to 25. One `signal` cancels the entire batch.
|
|
39
40
|
|
|
41
|
+
## Reference target types
|
|
42
|
+
|
|
43
|
+
Reference targets are checked against the field's `to` types by default.
|
|
44
|
+
Set `validateReferenceTypes: false` to disable these checks and their network reads.
|
|
45
|
+
If a target's type cannot be checked, validation is marked incomplete.
|
|
46
|
+
|
|
40
47
|
## Cancellation
|
|
41
48
|
|
|
42
49
|
```ts
|
package/lib/_internal.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
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-
|
|
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";
|
|
2
2
|
import { Path, Rule as Rule$1, RuleClass, Schema, SchemaType, SchemaValidationValue, ValidationContext as ValidationContext$1, ValidationError, ValidationMarker } from "@sanity/types";
|
|
3
|
+
import { accepts } from "@sanity/util/accepts";
|
|
3
4
|
export declare function getFallbackLocaleSource(): LocaleSource;
|
|
4
5
|
export declare const validationLocaleStrings: {
|
|
5
6
|
readonly 'array.exact-length': 'Must have exactly {{wantedLength}} items';
|
|
@@ -32,6 +33,7 @@ export declare const validationLocaleStrings: {
|
|
|
32
33
|
readonly 'object.not-media-library-asset': 'Must be a reference to a Media Library asset';
|
|
33
34
|
readonly 'object.not-reference': 'Must be a reference to a document';
|
|
34
35
|
readonly 'object.reference-not-published': 'Referenced document must be published';
|
|
36
|
+
readonly 'object.reference-target-type-mismatch': 'Referenced document has type "{{actualType}}"; expected one of: {{allowedTypes}}';
|
|
35
37
|
readonly 'slug.missing-current': 'Slug must have a value';
|
|
36
38
|
readonly 'slug.not-object': 'Slug must be an object';
|
|
37
39
|
readonly 'slug.not-unique': 'Slug is already in use';
|
|
@@ -87,22 +89,6 @@ export declare function hasValidationContext(validation: SchemaValidationValue |
|
|
|
87
89
|
* @internal
|
|
88
90
|
*/
|
|
89
91
|
export declare const Rule: RuleClass;
|
|
90
|
-
/**
|
|
91
|
-
* Check if the provided file type should be accepted by the input with accept attribute.
|
|
92
|
-
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input#attr-accept
|
|
93
|
-
*
|
|
94
|
-
* Inspired by https://github.com/enyo/dropzone (MIT) (c) 2021 Matias Meno
|
|
95
|
-
* Based on https://github.com/react-dropzone/attr-accept (MIT) (c) 2015 Andrey Okonetchnikov
|
|
96
|
-
*
|
|
97
|
-
* @param file - https://developer.mozilla.org/en-US/docs/Web/API/File
|
|
98
|
-
* @param acceptedFiles - List of accepted mime types (comma-separated string or array)
|
|
99
|
-
* @returns True if file is accepted, false otherwise
|
|
100
|
-
* @internal
|
|
101
|
-
*/
|
|
102
|
-
export declare function accepts(file: {
|
|
103
|
-
type: string;
|
|
104
|
-
name?: string;
|
|
105
|
-
}, acceptedFiles: string | string[]): boolean;
|
|
106
92
|
export declare function convertToValidationMarker(validatorResult: true | true[] | string | string[] | ValidationError | ValidationError[], level: 'error' | 'warning' | 'info' | undefined, context: ValidationContext, fallback?: {
|
|
107
93
|
code: ValidationMarkerCode;
|
|
108
94
|
details?: Record<string, unknown>;
|
|
@@ -111,5 +97,5 @@ export declare function getTypeChain(type: SchemaType | undefined, visited?: Set
|
|
|
111
97
|
export declare function normalizeValidationRules(typeDef: SchemaType | undefined, context?: ValidationContext$1): Rule$1[];
|
|
112
98
|
export declare function pathToString(path?: Path | undefined): string;
|
|
113
99
|
export declare function typeString(obj: unknown): string;
|
|
114
|
-
export { type LocaleSource, type ValidateDocumentInternalOptions, type ValidateDocumentObservableOptions, type ValidateItemOptions, type ValidationContext, type ValidationScheduling, evaluateDocumentInternal, evaluateDocumentObservable, resolveTypeForArrayItem, validateDocumentInternal, validateDocumentObservable, validateItem };
|
|
100
|
+
export { type LocaleSource, type ValidateDocumentInternalOptions, type ValidateDocumentObservableOptions, type ValidateItemOptions, type ValidationContext, type ValidationScheduling, accepts, evaluateDocumentInternal, evaluateDocumentObservable, resolveTypeForArrayItem, validateDocumentInternal, validateDocumentObservable, validateItem };
|
|
115
101
|
//# sourceMappingURL=_internal.d.ts.map
|
package/lib/_internal.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { _ as
|
|
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-B0K7YlIj.js";
|
|
2
|
+
import { accepts } from "@sanity/util/accepts";
|
|
2
3
|
function inferFromSchemaType(typeDef) {
|
|
3
4
|
return traverse(typeDef, /* @__PURE__ */ new Set()), typeDef;
|
|
4
5
|
}
|
package/lib/_internal.js.map
CHANGED
|
@@ -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":"
|
|
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"}
|
package/lib/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as validationMarkerCodes, 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-
|
|
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";
|
|
2
2
|
import { SanityDocument } from "@sanity/types";
|
|
3
3
|
type DocumentCheck = (options: {
|
|
4
4
|
id: string;
|
|
@@ -21,5 +21,5 @@ 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 ValidationMarkerCode, type ValidationSchema, type ValidationSource, validateDocument, validateDocumentWithWorkspace, validateDocuments, validationMarkerCodes };
|
|
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
25
|
//# sourceMappingURL=index.d.ts.map
|
package/lib/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { i as validateDocument, s as validateDocumentWithWorkspace, c as validateDocuments,
|
|
1
|
+
export { i as validateDocument, s as validateDocumentWithWorkspace, c as validateDocuments, b as validationMarkerCodes, u as withReleaseReferences } from "./validateDocument-B0K7YlIj.js";
|
|
@@ -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";
|
|
@@ -13,6 +13,7 @@ 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",
|
|
@@ -218,6 +221,39 @@ function createBatchedGetDocumentExists(client, defaultSignal) {
|
|
|
218
221
|
});
|
|
219
222
|
};
|
|
220
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
|
+
}
|
|
221
257
|
function pathToString(path = []) {
|
|
222
258
|
return path.reduce((target, segment, i) => {
|
|
223
259
|
let segmentType = typeof segment;
|
|
@@ -633,17 +669,36 @@ const dateValidators = {
|
|
|
633
669
|
message: message || i18n.t("validation:object.not-reference")
|
|
634
670
|
};
|
|
635
671
|
if (!type) throw Error("`type` was not provided in validation context");
|
|
636
|
-
|
|
672
|
+
let getDocumentType = context.__internal?.getDocumentType, weak = "weak" in type && type.weak;
|
|
673
|
+
if (weak && !getDocumentType) return !0;
|
|
637
674
|
if (!getDocumentExists) throw Error("`getDocumentExists` was not provided in validation context");
|
|
638
|
-
let
|
|
639
|
-
return documentId && value._ref == getPublishedId(documentId) || await getDocumentExists({
|
|
675
|
+
let selfReference = document?._id && value._ref === getPublishedId(document._id), exists = selfReference || await getDocumentExists({
|
|
640
676
|
id: value._ref,
|
|
641
677
|
signal: context.signal
|
|
642
|
-
})
|
|
678
|
+
});
|
|
679
|
+
if (!exists && !weak) return {
|
|
643
680
|
code: validationMarkerCodes.referenceNotPublished,
|
|
644
681
|
details: { referenceId: value._ref },
|
|
645
682
|
message: i18n.t("validation:object.reference-not-published", { documentId: value._ref })
|
|
646
683
|
};
|
|
684
|
+
if (exists && getDocumentType && isReferenceSchemaType(type)) {
|
|
685
|
+
let actualType = selfReference ? document?._type : await getDocumentType(value._ref);
|
|
686
|
+
if (!actualType) throw Error(`Could not read the type of referenced document "${value._ref}"`);
|
|
687
|
+
let allowedTypes = type.to.map((target) => target.name);
|
|
688
|
+
if (!allowedTypes.includes(actualType)) return {
|
|
689
|
+
code: validationMarkerCodes.referenceTargetTypeMismatch,
|
|
690
|
+
details: {
|
|
691
|
+
referenceId: value._ref,
|
|
692
|
+
actualType,
|
|
693
|
+
allowedTypes
|
|
694
|
+
},
|
|
695
|
+
message: i18n.t("validation:object.reference-target-type-mismatch", {
|
|
696
|
+
actualType,
|
|
697
|
+
allowedTypes: allowedTypes.join(", ")
|
|
698
|
+
})
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
return !0;
|
|
647
702
|
},
|
|
648
703
|
assetRequired: (flag, value, message, { i18n }) => !value || !value.asset || !value.asset._ref ? {
|
|
649
704
|
__internal_metadata: { name: "assetRequired" },
|
|
@@ -759,7 +814,23 @@ async function validateSlugUniqueness(value, context, isUnique) {
|
|
|
759
814
|
const slugUniquenessValidator = (value, context) => {
|
|
760
815
|
let options = context.type?.options;
|
|
761
816
|
return validateSlugUniqueness(value, context, hasCustomSlugUniqueness(options) ? options.isUnique : defaultIsUnique);
|
|
762
|
-
}, DUMMY_ORIGIN = "http://sanity", isRelativeUrl = (url) => /^\.*\//.test(url),
|
|
817
|
+
}, DUMMY_ORIGIN = "http://sanity", isRelativeUrl = (url) => /^\.*\//.test(url), SPECIAL_SCHEMES = /* @__PURE__ */ new Set([
|
|
818
|
+
"http:",
|
|
819
|
+
"https:",
|
|
820
|
+
"ws:",
|
|
821
|
+
"wss:",
|
|
822
|
+
"ftp:",
|
|
823
|
+
"file:"
|
|
824
|
+
]), FORBIDDEN_DOMAIN_CODE_POINT = /[\p{Cc} #/:<>?@[\\\]^|%]/u;
|
|
825
|
+
function hasInvalidDomain(url) {
|
|
826
|
+
if (!SPECIAL_SCHEMES.has(url.protocol) || url.hostname.startsWith("[")) return !1;
|
|
827
|
+
try {
|
|
828
|
+
return FORBIDDEN_DOMAIN_CODE_POINT.test(decodeURIComponent(url.hostname));
|
|
829
|
+
} catch {
|
|
830
|
+
return !0;
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
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
834
|
Boolean: booleanValidators,
|
|
764
835
|
Number: numberValidators,
|
|
765
836
|
String: {
|
|
@@ -794,15 +865,16 @@ const slugUniquenessValidator = (value, context) => {
|
|
|
794
865
|
uri: (constraints, value, message, { i18n }) => {
|
|
795
866
|
let strValue = value || "";
|
|
796
867
|
if (!strValue) return !0;
|
|
797
|
-
let { options } = constraints, { allowCredentials, relativeOnly } = options, allowRelative = options.allowRelative || relativeOnly,
|
|
868
|
+
let { options } = constraints, { allowCredentials, relativeOnly } = options, allowRelative = options.allowRelative || relativeOnly, invalidUrl = {
|
|
869
|
+
code: validationMarkerCodes.stringUrlInvalid,
|
|
870
|
+
message: message || i18n.t("validation:string.url.invalid")
|
|
871
|
+
}, url;
|
|
798
872
|
try {
|
|
799
873
|
url = allowRelative ? new URL(strValue, DUMMY_ORIGIN) : new URL(strValue);
|
|
800
874
|
} catch {
|
|
801
|
-
return
|
|
802
|
-
code: validationMarkerCodes.stringUrlInvalid,
|
|
803
|
-
message: message || i18n.t("validation:string.url.invalid")
|
|
804
|
-
};
|
|
875
|
+
return invalidUrl;
|
|
805
876
|
}
|
|
877
|
+
if (hasInvalidDomain(url)) return invalidUrl;
|
|
806
878
|
if (relativeOnly && url.origin !== DUMMY_ORIGIN) return {
|
|
807
879
|
code: validationMarkerCodes.stringUrlNotRelative,
|
|
808
880
|
message: message || i18n.t("validation:string.url.not-relative")
|
|
@@ -894,7 +966,7 @@ const slugUniquenessValidator = (value, context) => {
|
|
|
894
966
|
}
|
|
895
967
|
let message = isLocalizedMessages(this._message) ? localizeMessage(this._message, context.i18n) : this._message;
|
|
896
968
|
try {
|
|
897
|
-
let validatorContext = curr.flag === "all" || curr.flag === "either" ? {
|
|
969
|
+
let validatorContext = curr.flag === "reference" || curr.flag === "all" || curr.flag === "either" ? {
|
|
898
970
|
...context,
|
|
899
971
|
__internal
|
|
900
972
|
} : context;
|
|
@@ -909,28 +981,7 @@ const slugUniquenessValidator = (value, context) => {
|
|
|
909
981
|
}
|
|
910
982
|
}))).flat();
|
|
911
983
|
}
|
|
912
|
-
};
|
|
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
|
-
});
|
|
932
|
-
}
|
|
933
|
-
const resolvedFileTypes = /* @__PURE__ */ new Map();
|
|
984
|
+
}, resolvedFileTypes = /* @__PURE__ */ new Map();
|
|
934
985
|
function isUnknownFileType(fileType) {
|
|
935
986
|
return [fileType.mimeType, fileType.extension].every((value) => (value ?? "") === "");
|
|
936
987
|
}
|
|
@@ -941,10 +992,14 @@ function isUnknownFileType(fileType) {
|
|
|
941
992
|
* @internal
|
|
942
993
|
*/
|
|
943
994
|
function assetMatchesAccept(fileType, accept) {
|
|
995
|
+
let type = fileType.mimeType ?? "";
|
|
944
996
|
return accepts({
|
|
945
|
-
type
|
|
997
|
+
type,
|
|
946
998
|
name: getAssetFilename(fileType)
|
|
947
|
-
}, accept)
|
|
999
|
+
}, accept) || !!(fileType.extension && accepts({
|
|
1000
|
+
type,
|
|
1001
|
+
name: `asset.${fileType.extension}`
|
|
1002
|
+
}, accept));
|
|
948
1003
|
}
|
|
949
1004
|
function getAssetFilename(fileType) {
|
|
950
1005
|
return fileType.originalFilename ? fileType.originalFilename : fileType.extension ? `asset.${fileType.extension}` : void 0;
|
|
@@ -1179,8 +1234,17 @@ function createPace(scheduling) {
|
|
|
1179
1234
|
* @beta
|
|
1180
1235
|
*/
|
|
1181
1236
|
function withReleaseReferences({ document, getDocumentExists, isUnpublished }) {
|
|
1237
|
+
let resolveReference = createReferenceResolver({
|
|
1238
|
+
document,
|
|
1239
|
+
getDocumentExists,
|
|
1240
|
+
isUnpublished
|
|
1241
|
+
});
|
|
1242
|
+
return async (options) => await resolveReference(options) !== void 0;
|
|
1243
|
+
}
|
|
1244
|
+
/** Resolve the exact published or release document ID used by reference validation. */
|
|
1245
|
+
function createReferenceResolver({ document, getDocumentExists, isUnpublished }) {
|
|
1182
1246
|
let id = document._id, variant = document._system?.variants?.[0]?._ref ?? document._system?.variant?._ref;
|
|
1183
|
-
if (!isVersionId(id) || variant) return getDocumentExists;
|
|
1247
|
+
if (!isVersionId(id) || variant) return async (options) => await getDocumentExists(options) ? options.id : void 0;
|
|
1184
1248
|
let versionName = getVersionNameFromId(id);
|
|
1185
1249
|
return async ({ id: referenceId, signal }) => {
|
|
1186
1250
|
let versionId = getVersionId(referenceId, versionName), [versionExists, publishedExists] = await Promise.all([getDocumentExists({
|
|
@@ -1190,10 +1254,10 @@ function withReleaseReferences({ document, getDocumentExists, isUnpublished }) {
|
|
|
1190
1254
|
id: referenceId,
|
|
1191
1255
|
signal
|
|
1192
1256
|
})]);
|
|
1193
|
-
return versionExists ?
|
|
1257
|
+
return versionExists ? await isUnpublished({
|
|
1194
1258
|
id: versionId,
|
|
1195
1259
|
signal
|
|
1196
|
-
}) : publishedExists;
|
|
1260
|
+
}) ? void 0 : versionId : publishedExists ? referenceId : void 0;
|
|
1197
1261
|
};
|
|
1198
1262
|
}
|
|
1199
1263
|
/**
|
|
@@ -1256,7 +1320,7 @@ function resolveTypeForArrayItem(item, candidates) {
|
|
|
1256
1320
|
* @beta
|
|
1257
1321
|
* @deprecated Prefer {@link validateDocument} with `{document, schema, client}` for new code.
|
|
1258
1322
|
*/
|
|
1259
|
-
function validateDocumentWithWorkspace({ document, workspace, getClient = workspace.getClient, getDocumentExists, environment = "studio", maxCustomValidationConcurrency, maxFetchConcurrency, currentUser, customValidation, signal }) {
|
|
1323
|
+
function validateDocumentWithWorkspace({ document, workspace, getClient = workspace.getClient, getDocumentExists, environment = "studio", maxCustomValidationConcurrency, maxFetchConcurrency, currentUser, customValidation, signal, validateReferenceTypes = !0 }) {
|
|
1260
1324
|
return validateDocumentInternal({
|
|
1261
1325
|
currentUser,
|
|
1262
1326
|
customValidation,
|
|
@@ -1268,7 +1332,8 @@ function validateDocumentWithWorkspace({ document, workspace, getClient = worksp
|
|
|
1268
1332
|
maxCustomValidationConcurrency,
|
|
1269
1333
|
maxFetchConcurrency,
|
|
1270
1334
|
schema: workspace.schema,
|
|
1271
|
-
signal
|
|
1335
|
+
signal,
|
|
1336
|
+
validateReferenceTypes
|
|
1272
1337
|
});
|
|
1273
1338
|
}
|
|
1274
1339
|
/**
|
|
@@ -1300,14 +1365,14 @@ function validateDocuments(options) {
|
|
|
1300
1365
|
});
|
|
1301
1366
|
}
|
|
1302
1367
|
function normalizeValidationOptions(options) {
|
|
1303
|
-
let { client, customValidation = !!options.client, getDocumentExists, schema, ...internalOptions } = options;
|
|
1368
|
+
let { client, customValidation = !!options.client, getDocumentExists, i18n, schema, ...internalOptions } = options;
|
|
1304
1369
|
return {
|
|
1305
1370
|
...internalOptions,
|
|
1306
1371
|
customValidation,
|
|
1307
1372
|
environment: "cli",
|
|
1308
1373
|
getClient: client ? ({ apiVersion }) => client.withConfig({ apiVersion }) : throwClientUnavailable,
|
|
1309
1374
|
getDocumentExists: getDocumentExists || (client ? void 0 : throwClientUnavailable),
|
|
1310
|
-
i18n: getFallbackLocaleSource(),
|
|
1375
|
+
i18n: i18n ?? getFallbackLocaleSource(),
|
|
1311
1376
|
schema
|
|
1312
1377
|
};
|
|
1313
1378
|
}
|
|
@@ -1344,16 +1409,12 @@ function evaluateDocumentInternal(options) {
|
|
|
1344
1409
|
...sharedOptions
|
|
1345
1410
|
}).then(([result]) => result);
|
|
1346
1411
|
}
|
|
1347
|
-
function evaluateDocumentsInternal({ documents, schema, getClient, getDocumentExists, i18n = getFallbackLocaleSource(), environment, maxCustomValidationConcurrency, maxFetchConcurrency, currentUser, customValidation = !0, signal }) {
|
|
1412
|
+
function evaluateDocumentsInternal({ documents, schema, getClient, getDocumentExists, i18n = getFallbackLocaleSource(), environment, maxCustomValidationConcurrency, maxFetchConcurrency, currentUser, customValidation = !0, signal, validateReferenceTypes = !0 }) {
|
|
1348
1413
|
if (signal?.aborted) return Promise.reject(signal.reason);
|
|
1349
1414
|
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) =>
|
|
1352
|
-
|
|
1353
|
-
getClient: getConcurrencyLimitedClient,
|
|
1354
|
-
i18n,
|
|
1355
|
-
schema,
|
|
1356
|
-
getDocumentExists: batchedGetDocumentExists ? withReleaseReferences({
|
|
1415
|
+
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;
|
|
1416
|
+
return Promise.all(documents.map((document) => {
|
|
1417
|
+
let resolveReference = batchedGetDocumentExists ? createReferenceResolver({
|
|
1357
1418
|
document,
|
|
1358
1419
|
getDocumentExists: batchedGetDocumentExists,
|
|
1359
1420
|
isUnpublished: ({ id, signal: checkSignal }) => getConcurrencyLimitedClient(DEFAULT_VALIDATION_CLIENT_OPTIONS).fetch("*[_id == $id][0]._system.delete == true", { id }, {
|
|
@@ -1361,14 +1422,28 @@ function evaluateDocumentsInternal({ documents, schema, getClient, getDocumentEx
|
|
|
1361
1422
|
signal: checkSignal,
|
|
1362
1423
|
tag: "validation.release-reference"
|
|
1363
1424
|
})
|
|
1364
|
-
}) : getDocumentExists,
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1425
|
+
}) : async (options) => await getDocumentExists(options) ? options.id : void 0, resolvedReferences = /* @__PURE__ */ new Map();
|
|
1426
|
+
return evaluateDocument({
|
|
1427
|
+
document,
|
|
1428
|
+
getClient: getConcurrencyLimitedClient,
|
|
1429
|
+
i18n,
|
|
1430
|
+
schema,
|
|
1431
|
+
getDocumentExists: async (options) => {
|
|
1432
|
+
let resolvedId = await resolveReference(options);
|
|
1433
|
+
return batchedGetDocumentType && resolvedId && resolvedReferences.set(options.id, resolvedId), resolvedId !== void 0;
|
|
1434
|
+
},
|
|
1435
|
+
getDocumentType: batchedGetDocumentType ? async (id) => {
|
|
1436
|
+
let resolvedId = resolvedReferences.get(id);
|
|
1437
|
+
return resolvedId ? batchedGetDocumentType(resolvedId) : void 0;
|
|
1438
|
+
} : void 0,
|
|
1439
|
+
environment,
|
|
1440
|
+
maxCustomValidationConcurrency,
|
|
1441
|
+
currentUser,
|
|
1442
|
+
customValidation,
|
|
1443
|
+
signal,
|
|
1444
|
+
pace: createUnpacedPace()
|
|
1445
|
+
});
|
|
1446
|
+
}));
|
|
1372
1447
|
}
|
|
1373
1448
|
const customValidationConcurrencyLimiters = /* @__PURE__ */ new WeakMap();
|
|
1374
1449
|
/**
|
|
@@ -1404,7 +1479,7 @@ async function evaluateDocument(options) {
|
|
|
1404
1479
|
pace.dispose();
|
|
1405
1480
|
}
|
|
1406
1481
|
}
|
|
1407
|
-
async function evaluateDocumentWithoutCancellation({ document, getClient, i18n = getFallbackLocaleSource(), schema, getDocumentExists, environment, maxCustomValidationConcurrency, currentUser, customValidation = !0, signal, pace }) {
|
|
1482
|
+
async function evaluateDocumentWithoutCancellation({ document, getClient, i18n = getFallbackLocaleSource(), schema, getDocumentExists, getDocumentType, environment, maxCustomValidationConcurrency, currentUser, customValidation = !0, signal, pace }) {
|
|
1408
1483
|
try {
|
|
1409
1484
|
if (typeof document?._type != "string") throw Error("Tried to validate a value without a '_type'");
|
|
1410
1485
|
let documentType = schema.get(document._type);
|
|
@@ -1433,6 +1508,7 @@ async function evaluateDocumentWithoutCancellation({ document, getClient, i18n =
|
|
|
1433
1508
|
customValidation,
|
|
1434
1509
|
signal,
|
|
1435
1510
|
__internal: {
|
|
1511
|
+
getDocumentType,
|
|
1436
1512
|
markIncomplete: () => {
|
|
1437
1513
|
complete = !1;
|
|
1438
1514
|
},
|
|
@@ -1599,6 +1675,6 @@ function toDocumentValidationMarker(marker) {
|
|
|
1599
1675
|
code: validationMarkerCodes.validationFailed
|
|
1600
1676
|
};
|
|
1601
1677
|
}
|
|
1602
|
-
export {
|
|
1678
|
+
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 };
|
|
1603
1679
|
|
|
1604
|
-
//# sourceMappingURL=validateDocument-
|
|
1680
|
+
//# sourceMappingURL=validateDocument-B0K7YlIj.js.map
|