@sanity/validation 3.14.4 → 6.12.0-next.112

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +52 -0
  3. package/lib/_internal.d.ts +96 -0
  4. package/lib/_internal.js +39 -0
  5. package/lib/_internal.js.map +1 -0
  6. package/lib/index.d.ts +2 -0
  7. package/lib/index.js +2 -1306
  8. package/lib/validateDocument-6pLTIHIn.d.ts +277 -0
  9. package/lib/validateDocument-Cq33kUmN.js +1127 -0
  10. package/lib/validateDocument-Cq33kUmN.js.map +1 -0
  11. package/package.json +53 -45
  12. package/lib/dts/src/index.d.ts +0 -50
  13. package/lib/index.cjs.mjs +0 -9
  14. package/lib/index.esm.js +0 -1286
  15. package/lib/index.esm.js.map +0 -1
  16. package/lib/index.js.map +0 -1
  17. package/src/Rule.ts +0 -424
  18. package/src/ValidationError.ts +0 -32
  19. package/src/index.ts +0 -9
  20. package/src/inferFromSchema.ts +0 -19
  21. package/src/inferFromSchemaType.ts +0 -50
  22. package/src/util/convertToValidationMarker.ts +0 -84
  23. package/src/util/deepEquals.ts +0 -77
  24. package/src/util/escapeRegex.ts +0 -5
  25. package/src/util/normalizeValidationRules.test.ts +0 -170
  26. package/src/util/normalizeValidationRules.ts +0 -118
  27. package/src/util/pathToString.ts +0 -21
  28. package/src/util/requestIdleCallback.ts +0 -31
  29. package/src/util/typeString.test.ts +0 -27
  30. package/src/util/typeString.ts +0 -23
  31. package/src/validateDocument.test.ts +0 -703
  32. package/src/validateDocument.ts +0 -240
  33. package/src/validators/arrayValidator.ts +0 -100
  34. package/src/validators/booleanValidator.ts +0 -16
  35. package/src/validators/dateValidator.ts +0 -113
  36. package/src/validators/genericValidator.ts +0 -117
  37. package/src/validators/numberValidator.ts +0 -66
  38. package/src/validators/objectValidator.ts +0 -64
  39. package/src/validators/slugValidator.ts +0 -117
  40. package/src/validators/stringValidator.ts +0 -120
@@ -0,0 +1,277 @@
1
+ import { CurrentUser, SanityDocument, Schema, SchemaType, ValidationContext as ValidationContext$1, ValidationMarker } from "@sanity/types";
2
+ import { ConcurrencyLimiter } from "@sanity/util/concurrency-limiter";
3
+ import { Observable } from "rxjs";
4
+ import { TFunction } from "i18next";
5
+ import { SanityClient } from "@sanity/client";
6
+ interface LocaleSource {
7
+ currentLocale: {
8
+ id: string;
9
+ };
10
+ loadNamespaces(namespaces: string[]): Promise<void>;
11
+ t: TFunction;
12
+ }
13
+ declare module '@sanity/types' {
14
+ /**
15
+ * Extended validation context that includes internationalization
16
+ *
17
+ * Why is this not directly part of `@sanity/types`, you ask?
18
+ * Because `@sanity/types` shouldn't need to depend on the `i18next` package, which it needs
19
+ * for the `TFunction` type. The `ValidationContext` should never have been part of the types
20
+ * module in the first place, but is now unfortunately part of the public API and thus cannot
21
+ * be changed easily.
22
+ *
23
+ * This is a temporary solution until we can remove the `ValidationContext` from the types module,
24
+ * which is likely to happen at the next major version.
25
+ *
26
+ * @public
27
+ */
28
+ interface ValidationContext {
29
+ /**
30
+ * Internationalization utilities, for translation of validation messages
31
+ *
32
+ * See {@link LocaleSource} for details.
33
+ */
34
+ i18n: LocaleSource;
35
+ }
36
+ }
37
+ /** Machine-readable codes emitted by built-in document validation. @beta */
38
+ declare const validationMarkerCodes: {
39
+ readonly arrayDuplicateItem: 'array.duplicate-item';
40
+ readonly arrayExactLength: 'array.exact-length';
41
+ readonly arrayMaximumLength: 'array.maximum-length';
42
+ readonly arrayMinimumLength: 'array.minimum-length';
43
+ readonly assetRequired: 'asset.required';
44
+ readonly custom: 'custom';
45
+ readonly dateInvalidFormat: 'date.invalid-format';
46
+ readonly dateMaximum: 'date.maximum';
47
+ readonly dateMinimum: 'date.minimum';
48
+ readonly documentUnknownType: 'document.unknown-type';
49
+ readonly mediaCustom: 'media.custom';
50
+ readonly mediaInvalidReference: 'media.invalid-reference';
51
+ readonly mediaNotFound: 'media.not-found';
52
+ readonly numberGreaterThan: 'number.greater-than';
53
+ readonly numberInteger: 'number.integer';
54
+ readonly numberLessThan: 'number.less-than';
55
+ readonly numberMaximum: 'number.maximum';
56
+ readonly numberMinimum: 'number.minimum';
57
+ readonly numberPrecision: 'number.precision';
58
+ readonly objectUnknownField: 'object.unknown-field';
59
+ readonly referenceInvalid: 'reference.invalid';
60
+ readonly referenceNotPublished: 'reference.not-published';
61
+ readonly ruleAllFailed: 'rule.all-failed';
62
+ readonly ruleEitherFailed: 'rule.either-failed';
63
+ readonly slugInvalidType: 'slug.invalid-type';
64
+ readonly slugMissingCurrent: 'slug.missing-current';
65
+ readonly slugNotUnique: 'slug.not-unique';
66
+ readonly stringEmail: 'string.email';
67
+ readonly stringExactLength: 'string.exact-length';
68
+ readonly stringLowercase: 'string.lowercase';
69
+ readonly stringMaximumLength: 'string.maximum-length';
70
+ readonly stringMinimumLength: 'string.minimum-length';
71
+ readonly stringRegexMatch: 'string.regex-match';
72
+ readonly stringRegexMismatch: 'string.regex-mismatch';
73
+ readonly stringUppercase: 'string.uppercase';
74
+ readonly stringUrlCredentialsNotAllowed: 'string.url.credentials-not-allowed';
75
+ readonly stringUrlInvalid: 'string.url.invalid';
76
+ readonly stringUrlNotAbsolute: 'string.url.not-absolute';
77
+ readonly stringUrlNotRelative: 'string.url.not-relative';
78
+ readonly stringUrlSchemeNotAllowed: 'string.url.scheme-not-allowed';
79
+ readonly validationException: 'validation.exception';
80
+ readonly validationFailed: 'validation.failed';
81
+ readonly valueNotAllowed: 'value.not-allowed';
82
+ readonly valueRequired: 'value.required';
83
+ readonly valueTypeMismatch: 'value.type-mismatch';
84
+ };
85
+ /** A code emitted by a built-in validator. @beta */
86
+ type BuiltInValidationMarkerCode = (typeof validationMarkerCodes)[keyof typeof validationMarkerCodes];
87
+ /**
88
+ * A built-in validation code or an application-defined custom code.
89
+ * Custom validators should namespace their codes, for example `custom.seo-title`.
90
+ * @beta
91
+ */
92
+ type ValidationMarkerCode = BuiltInValidationMarkerCode | (string & {});
93
+ /** A validation marker emitted by `validateDocument`, which always has a code. @beta */
94
+ type DocumentValidationMarker = Omit<ValidationMarker, 'code'> & {
95
+ code: ValidationMarkerCode;
96
+ };
97
+ /**
98
+ * @internal
99
+ */
100
+ declare function resolveTypeForArrayItem(item: unknown, candidates: SchemaType[]): SchemaType | undefined;
101
+ /**
102
+ * @beta
103
+ */
104
+ interface ValidateDocumentOptions {
105
+ /**
106
+ * The document to be validated
107
+ */
108
+ document: SanityDocument;
109
+ /** The compiled schema to validate against. */
110
+ schema: ValidationSchema;
111
+ /** A configured client used for reference checks and custom validators. */
112
+ client: ValidationClient;
113
+ /**
114
+ * Function used to check if referenced documents exists (and is published).
115
+ *
116
+ * If you're validating many documents in bulk, you may want to query for all
117
+ * document IDs first and provide your own implementation using those.
118
+ *
119
+ * If no function is provided a default one will be provided that will batch
120
+ * call the `doc` endpoint to check for document existence.
121
+ */
122
+ getDocumentExists?: (options: {
123
+ id: string;
124
+ }) => Promise<boolean>;
125
+ /**
126
+ * The maximum amount of custom validation functions to be running
127
+ * concurrently at once. This helps prevent custom validators from
128
+ * overwhelming backend services (e.g. called via fetch) used in async,
129
+ * user-defined validation functions. (i.e. `rule.custom(async() => {})`)
130
+ *
131
+ * Note that lowering this number may also help in cases where a custom
132
+ * validator could potentially exhaust the fetch concurrency. This is 5 by
133
+ * default.
134
+ */
135
+ maxCustomValidationConcurrency?: number;
136
+ /**
137
+ * The amount of allowed inflight fetch requests at once for this validation.
138
+ * You may need to up this value if you have complex custom validations that
139
+ * require many `client.fetch` requests at once. It's possible for a custom
140
+ * validator to stall if there are not enough concurrent fetch requests
141
+ * available to fulfill the custom validation. Must be a positive integer.
142
+ * This is 25 by default.
143
+ */
144
+ maxFetchConcurrency?: number;
145
+ /**
146
+ * The current user, when available. Used when resolving schema `hidden`
147
+ * conditionals so validation matches what the form shows. If omitted, hidden
148
+ * is resolved with no user (e.g. CLI or headless validation).
149
+ */
150
+ currentUser?: Omit<CurrentUser, 'role'> | null;
151
+ }
152
+ /** A compiled schema accepted across compatible `@sanity/types` versions. @beta */
153
+ interface ValidationSchema {
154
+ get(name: string): unknown;
155
+ }
156
+ /**
157
+ * A configured Sanity client accepted across compatible client versions.
158
+ *
159
+ * This structural type describes the capabilities used internally by validation.
160
+ * The configured client is exposed to custom validators as a `SanityClient`, so it must be compatible with the full client API.
161
+ *
162
+ * @beta
163
+ */
164
+ interface ValidationClient {
165
+ fetch: SanityClient['fetch'];
166
+ getDataUrl: SanityClient['getDataUrl'];
167
+ observable: Pick<SanityClient['observable'], 'fetch' | 'request'>;
168
+ withConfig(config: Parameters<SanityClient['withConfig']>[0]): ValidationClient;
169
+ }
170
+ /**
171
+ * The validation capabilities required from a resolved Studio source or workspace.
172
+ *
173
+ * @beta
174
+ */
175
+ interface ValidationSource {
176
+ /** The compiled schema to validate against. */
177
+ schema: Schema;
178
+ /** Factory used to get the client passed to custom validators. */
179
+ getClient: (clientOptions: {
180
+ apiVersion: string;
181
+ }) => SanityClient;
182
+ /** Internationalization utilities used for validation messages. */
183
+ i18n: LocaleSource;
184
+ }
185
+ /**
186
+ * Options accepted by the compatibility overload for Studio workspace validation.
187
+ *
188
+ * @beta
189
+ */
190
+ interface ValidateDocumentWorkspaceOptions extends Omit<ValidateDocumentOptions, 'client' | 'schema'> {
191
+ /** The resolved Studio workspace or source used for validation. */
192
+ workspace: ValidationSource;
193
+ /**
194
+ * Factory used to get the client passed to custom validators.
195
+ *
196
+ * @deprecated For internal use only
197
+ */
198
+ getClient?: ValidationSource['getClient'];
199
+ /** Validation environment exposed to custom validators. */
200
+ environment?: 'cli' | 'studio';
201
+ }
202
+ /**
203
+ * Validates a document against the schema in a resolved Studio workspace or source.
204
+ *
205
+ * @beta
206
+ * @deprecated Prefer {@link validateDocument} with `{document, schema, client}` for new code.
207
+ */
208
+ declare function validateDocumentWithWorkspace({ document, workspace, getClient, getDocumentExists, environment, maxCustomValidationConcurrency, maxFetchConcurrency, currentUser }: ValidateDocumentWorkspaceOptions): Promise<DocumentValidationMarker[]>;
209
+ /**
210
+ * Validates a document against the schema in a resolved Studio workspace or source.
211
+ *
212
+ * This compatibility overload preserves the existing `sanity` API. Prefer the
213
+ * `{document, schema, client}` overload for new code.
214
+ *
215
+ * @beta
216
+ */
217
+ declare function validateDocument(options: ValidateDocumentWorkspaceOptions): Promise<DocumentValidationMarker[]>;
218
+ /**
219
+ * Validates a document against a compiled schema. Returns validation markers
220
+ * without deciding whether the document may be edited or published.
221
+ *
222
+ * @beta
223
+ */
224
+ declare function validateDocument(options: ValidateDocumentOptions): Promise<DocumentValidationMarker[]>;
225
+ /** @internal */
226
+ interface ValidateDocumentInternalOptions {
227
+ document: SanityDocument;
228
+ schema: Schema;
229
+ getClient: (clientOptions: {
230
+ apiVersion: string;
231
+ }) => SanityClient;
232
+ getDocumentExists?: (options: {
233
+ id: string;
234
+ }) => Promise<boolean>;
235
+ i18n?: LocaleSource;
236
+ environment: 'cli' | 'studio';
237
+ maxCustomValidationConcurrency?: number;
238
+ maxFetchConcurrency?: number;
239
+ currentUser?: Omit<CurrentUser, 'role'> | null;
240
+ }
241
+ /** @internal */
242
+ declare function validateDocumentInternal({ document, schema, getClient, getDocumentExists, i18n, environment, maxCustomValidationConcurrency, maxFetchConcurrency, currentUser }: ValidateDocumentInternalOptions): Promise<DocumentValidationMarker[]>;
243
+ /**
244
+ * @internal
245
+ */
246
+ interface ValidateDocumentObservableOptions extends Pick<ValidationContext$1, 'getDocumentExists' | 'i18n'> {
247
+ getClient: (options: {
248
+ apiVersion: string;
249
+ }) => SanityClient;
250
+ document: SanityDocument;
251
+ schema: Schema;
252
+ environment: 'cli' | 'studio';
253
+ maxCustomValidationConcurrency?: number;
254
+ currentUser?: Omit<CurrentUser, 'role'> | null;
255
+ }
256
+ /**
257
+ * Validates a document against the given schema, returning an Observable
258
+ * @internal
259
+ */
260
+ declare function validateDocumentObservable({ document, getClient, i18n, schema, getDocumentExists, environment, maxCustomValidationConcurrency, currentUser }: ValidateDocumentObservableOptions): Observable<DocumentValidationMarker[]>;
261
+ /**
262
+ * this is used make optional properties required by replacing optionals with
263
+ * `T[P] | undefined`. this is used to prevent errors in `validateItem` where
264
+ * an option from a previous invocation would be incorrectly passed down.
265
+ *
266
+ * https://medium.com/terria/typescript-transforming-optional-properties-to-required-properties-that-may-be-undefined-7482cb4e1585
267
+ */
268
+ type ExplicitUndefined<T> = { [P in keyof Required<T>]: Pick<T, P> extends Required<Pick<T, P>> ? T[P] : T[P] | undefined; };
269
+ type ValidateItemOptions = {
270
+ value: unknown;
271
+ customValidationConcurrencyLimiter?: ConcurrencyLimiter;
272
+ hidden?: boolean;
273
+ currentUser?: Omit<CurrentUser, 'role'> | null;
274
+ } & ExplicitUndefined<Omit<ValidationContext$1, 'hidden'>>;
275
+ declare function validateItem(opts: ValidateItemOptions): Promise<ValidationMarker[]>;
276
+ export { validationMarkerCodes as _, ValidationClient as a, resolveTypeForArrayItem as c, validateDocumentObservable as d, validateDocumentWithWorkspace as f, ValidationMarkerCode as g, DocumentValidationMarker as h, ValidateDocumentWorkspaceOptions as i, validateDocument as l, BuiltInValidationMarkerCode as m, ValidateDocumentObservableOptions as n, ValidationSchema as o, validateItem as p, ValidateDocumentOptions as r, ValidationSource as s, ValidateDocumentInternalOptions as t, validateDocumentInternal as u, ValidationContext$1 as v, LocaleSource as y };
277
+ //# sourceMappingURL=validateDocument-6pLTIHIn.d.ts.map