@sanity/validation 3.14.4 → 6.12.0-next.46

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 +29 -0
  3. package/lib/_internal.d.ts +93 -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-C77_Oewa.js +843 -0
  9. package/lib/validateDocument-C77_Oewa.js.map +1 -0
  10. package/lib/validateDocument-CBOsd748.d.ts +199 -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
@@ -1,703 +0,0 @@
1
- import {
2
- ArraySchemaType,
3
- PortableTextTextBlock,
4
- Rule,
5
- SanityDocument,
6
- Schema,
7
- SchemaType,
8
- ValidationContext,
9
- } from '@sanity/types'
10
- import {createSchema} from '../test/createSchema'
11
- import {createMockSanityClient} from '../test/mocks/mockSanityClient'
12
- import validateDocument, {resolveTypeForArrayItem, validateItem} from './validateDocument'
13
- import {convertToValidationMarker} from './util/convertToValidationMarker'
14
-
15
- jest.mock('./util/convertToValidationMarker', () => {
16
- return {
17
- convertToValidationMarker: jest.fn(
18
- jest.requireActual('./util/convertToValidationMarker').convertToValidationMarker
19
- ),
20
- }
21
- })
22
-
23
- beforeEach(() => {
24
- ;(convertToValidationMarker as jest.Mock).mockClear()
25
- })
26
-
27
- // mock client
28
- const client = createMockSanityClient() as any as ReturnType<ValidationContext['getClient']>
29
- const getClient = (options: {apiVersion: string}) => client
30
-
31
- describe('resolveTypeForArrayItem', () => {
32
- const schema: Schema = createSchema({
33
- types: [
34
- {
35
- name: 'foo',
36
- type: 'object',
37
- fields: [{name: 'title', type: 'number'}],
38
- },
39
- {
40
- name: 'bar',
41
- type: 'object',
42
- fields: [{name: 'title', type: 'string'}],
43
- },
44
- ],
45
- })
46
-
47
- const fooType = schema.get('foo')
48
- const barType = schema.get('bar')
49
-
50
- it('finds a matching schema type for an array item value given a list of candidate types', () => {
51
- const resolved = resolveTypeForArrayItem(
52
- {
53
- _type: 'bar',
54
- _key: 'exampleKey',
55
- title: 5,
56
- },
57
- [fooType!, barType!]
58
- )
59
-
60
- expect(resolved).toBe(barType)
61
- })
62
-
63
- it('assumes the type if there is only one possible candidate', () => {
64
- const resolved = resolveTypeForArrayItem(
65
- {
66
- // notice no _type
67
- _key: 'exampleKey',
68
- title: 5,
69
- },
70
- [fooType!]
71
- )
72
-
73
- expect(resolved).toBe(fooType)
74
- })
75
- })
76
-
77
- describe('validateDocument', () => {
78
- it('takes in a document + a compiled schema and returns a list of validation markers', async () => {
79
- const schema = createSchema({
80
- types: [
81
- {
82
- name: 'simpleDoc',
83
- type: 'document',
84
- title: 'Simple Document',
85
- fields: [
86
- {
87
- name: 'title',
88
- type: 'string',
89
- validation: (rule: Rule) => rule.required(),
90
- },
91
- ],
92
- },
93
- ],
94
- })
95
-
96
- const document: SanityDocument = {
97
- _id: 'testId',
98
- _createdAt: '2021-08-27T14:48:51.650Z',
99
- _rev: 'exampleRev',
100
- _type: 'simpleDoc',
101
- _updatedAt: '2021-08-27T14:48:51.650Z',
102
- title: null,
103
- }
104
-
105
- const result = await validateDocument(getClient, document, schema)
106
- expect(result).toMatchObject([
107
- {
108
- level: 'error',
109
- item: {
110
- message: 'Expected type "String", got "null"',
111
- paths: [],
112
- },
113
- path: ['title'],
114
- },
115
- {
116
- level: 'error',
117
- item: {
118
- message: 'Required',
119
- paths: [],
120
- },
121
- path: ['title'],
122
- },
123
- ])
124
- })
125
- })
126
-
127
- describe('validateItem', () => {
128
- it("runs nested validation on an undefined value for object types if it's required", async () => {
129
- const validation = (rule: Rule) => [
130
- rule.required().error('This is required!'),
131
- rule.max(160).warning('Too long!'),
132
- ]
133
-
134
- const schema = createSchema({
135
- types: [
136
- {
137
- name: 'testObj',
138
- type: 'object',
139
- title: 'Test Object',
140
- fields: [
141
- {name: 'registeredString', type: 'registeredString'},
142
- {name: 'inlineString', type: 'string', validation},
143
- {
144
- name: 'registeredObject',
145
- type: 'registeredObjectField',
146
- validation: (rule: Rule) => rule.required(),
147
- },
148
- {
149
- name: 'inlineObject',
150
- type: 'object',
151
- fields: [{name: 'foo', type: 'string', validation}],
152
- validation: (rule: Rule) => rule.required(),
153
- },
154
- {
155
- name: 'notRequiredRegisteredObject',
156
- type: 'registeredObjectField',
157
- },
158
- {
159
- name: 'notRequiredInlineObject',
160
- type: 'object',
161
- fields: [{name: 'foo', type: 'string', validation}],
162
- },
163
- ],
164
- },
165
- {name: 'registeredString', title: 'Registered String', type: 'string', validation},
166
- {
167
- title: 'Registered Object Field',
168
- name: 'registeredObjectField',
169
- type: 'object',
170
- fields: [{name: 'foo', type: 'string', validation}],
171
- },
172
- ],
173
- })
174
- // ensures there are no schema formatting issues
175
- expect(schema._validation).toHaveLength(0)
176
-
177
- await expect(
178
- validateItem({
179
- getClient,
180
- schema,
181
- value: {},
182
- document: undefined,
183
- path: [],
184
- parent: undefined,
185
- type: schema.get('testObj'),
186
- getDocumentExists: undefined,
187
- })
188
- ).resolves.toMatchObject([
189
- {
190
- level: 'error',
191
- item: {message: 'This is required!'},
192
- path: ['registeredString'],
193
- },
194
- {
195
- level: 'error',
196
- item: {message: 'This is required!'},
197
- path: ['inlineString'],
198
- },
199
- {
200
- level: 'error',
201
- item: {message: 'Required'},
202
- path: ['registeredObject'],
203
- },
204
- {
205
- level: 'error',
206
- item: {message: 'This is required!'},
207
- path: ['registeredObject', 'foo'],
208
- },
209
- {
210
- level: 'error',
211
- item: {message: 'Required'},
212
- path: ['inlineObject'],
213
- },
214
- {
215
- level: 'error',
216
- item: {message: 'This is required!'},
217
- path: ['inlineObject', 'foo'],
218
- },
219
- ])
220
- })
221
-
222
- it('runs nested validation for object-level rules set via Rule.fields()', async () => {
223
- const schema = createSchema({
224
- types: [
225
- {
226
- name: 'testObj',
227
- type: 'object',
228
- title: 'Test Object',
229
- fields: [
230
- {name: 'foo', type: 'string'},
231
- {name: 'bar', type: 'string'},
232
- ],
233
- validation: (rule: Rule) => [
234
- rule.required(),
235
- rule.fields({
236
- foo: (r) => r.required(),
237
- bar: (r) => r.required(),
238
- }),
239
- ],
240
- },
241
- ],
242
- })
243
-
244
- // ensures there are no schema formatting issues
245
- expect(schema._validation).toHaveLength(0)
246
-
247
- await expect(
248
- validateItem({
249
- getClient,
250
- schema,
251
- document: undefined,
252
- parent: undefined,
253
- path: undefined,
254
- type: schema.get('testObj'),
255
- value: {foo: 5},
256
- getDocumentExists: undefined,
257
- })
258
- ).resolves.toMatchObject([
259
- {
260
- item: {message: 'Expected type "String", got "Number"'},
261
- level: 'error',
262
- path: ['foo'],
263
- },
264
- {
265
- item: {message: 'Required'},
266
- level: 'error',
267
- path: ['bar'],
268
- },
269
- ])
270
- })
271
-
272
- // @todo this one fails, needs investigation for what is actually the expected outcome
273
- it.skip('runs nested validation for markDefs', async () => {
274
- const linkValidationSpy = jest.fn(() => true as const)
275
- const internalLinkSpy = jest.fn(() => 'mock invalid response')
276
-
277
- const schema = createSchema({
278
- types: [
279
- {
280
- name: 'post',
281
- title: 'Post',
282
- type: 'document',
283
- fields: [
284
- {name: 'title', type: 'string'},
285
- {name: 'body', type: 'string'},
286
- ],
287
- },
288
- {
289
- name: 'registeredEditor',
290
- type: 'object',
291
- title: 'Registered Editor',
292
- fields: [
293
- {
294
- name: 'editor',
295
- type: 'array',
296
- of: [
297
- {
298
- type: 'block',
299
- marks: {
300
- annotations: [
301
- {
302
- name: 'exampleAnnotation',
303
- type: 'object',
304
- fields: [{name: 'value', type: 'string'}],
305
- },
306
- ],
307
- },
308
- },
309
- ],
310
- },
311
- ],
312
- },
313
- {
314
- name: 'blockTest',
315
- type: 'document',
316
- title: 'blockTest',
317
- fields: [
318
- {
319
- name: 'content',
320
- title: 'Content',
321
- type: 'array',
322
- of: [
323
- {
324
- type: 'block',
325
- marks: {
326
- annotations: [
327
- {
328
- name: 'link',
329
- type: 'object',
330
- title: 'link',
331
- fields: [{name: 'url', type: 'url'}],
332
- validation: (rule: Rule) => rule.custom(linkValidationSpy),
333
- },
334
- {
335
- name: 'internalLink',
336
- type: 'object',
337
- title: 'Internal link',
338
- fields: [{name: 'reference', type: 'reference', to: [{type: 'post'}]}],
339
- validation: (rule: Rule) => rule.custom(internalLinkSpy),
340
- },
341
- {name: 'nestedEditor', type: 'registeredEditor'},
342
- ],
343
- },
344
- },
345
- ],
346
- },
347
- ],
348
- },
349
- ],
350
- })
351
-
352
- expect(schema._validation).toHaveLength(0)
353
-
354
- const nestedBlock: PortableTextTextBlock = {
355
- _type: 'block',
356
- _key: 'nested-block-key',
357
- children: [
358
- {
359
- _key: 'some-key',
360
- _type: 'span',
361
- text: 'hey',
362
- marks: ['example-annotation-key'],
363
- },
364
- ],
365
- markDefs: [
366
- {
367
- _type: 'exampleAnnotation',
368
- _key: 'example-annotation-key',
369
- value: 5,
370
- },
371
- ],
372
- style: 'normal',
373
- }
374
-
375
- const block: PortableTextTextBlock = {
376
- _key: 'block-key',
377
- _type: 'block',
378
- children: [
379
- {
380
- _key: 'child-0',
381
- _type: 'span',
382
- marks: ['0', '1', '2'],
383
- text: 'hey',
384
- },
385
- ],
386
- markDefs: [
387
- {
388
- _key: '0',
389
- _type: 'link',
390
- url: 'https://example.com',
391
- },
392
- {
393
- _key: '1',
394
- _type: 'internalLink',
395
- _ref: 'post-id',
396
- },
397
- {
398
- _key: '2',
399
- _type: 'nestedEditor',
400
- editor: [nestedBlock],
401
- },
402
- ],
403
- style: 'normal',
404
- }
405
-
406
- const document: SanityDocument = {
407
- _id: 'mock-id',
408
- _type: 'blockTest',
409
- _createdAt: '2021-11-15T21:06:41.812Z',
410
- _rev: 'example-ref',
411
- _updatedAt: '2021-11-15T21:06:41.812Z',
412
- content: [block],
413
- }
414
-
415
- const result = await validateItem({
416
- getClient,
417
- schema,
418
- document: document,
419
- parent: undefined,
420
- path: [],
421
- type: schema.get('blockTest'),
422
- value: document,
423
- getDocumentExists: undefined,
424
- })
425
-
426
- expect(result).toMatchObject([
427
- {
428
- item: {message: 'mock invalid response', paths: []},
429
- level: 'error',
430
- path: ['content', {_key: 'block-key'}, 'markDefs', {_key: '1'}],
431
- },
432
- // this tests for nested markDef validation
433
- {
434
- item: {
435
- message: 'Expected type "String", got "Number"',
436
- paths: [],
437
- },
438
- level: 'error',
439
- path: [
440
- 'content',
441
- {_key: 'block-key'},
442
- 'markDefs',
443
- {_key: '2'},
444
- 'editor',
445
- {_key: 'nested-block-key'},
446
- 'markDefs',
447
- {_key: 'example-annotation-key'},
448
- 'value',
449
- ],
450
- },
451
- ])
452
-
453
- expect(linkValidationSpy.mock.calls).toMatchObject([
454
- [
455
- {
456
- _key: '0',
457
- _type: 'link',
458
- url: 'https://example.com',
459
- },
460
- {
461
- document: {_id: 'mock-id'},
462
- parent: {_key: 'block-key'},
463
- path: ['content', {_key: 'block-key'}, 'markDefs', {_key: '0'}],
464
- type: {name: 'link'},
465
- },
466
- ],
467
- ])
468
-
469
- expect(internalLinkSpy.mock.calls).toMatchObject([
470
- [
471
- {
472
- _key: '1',
473
- _ref: 'post-id',
474
- _type: 'internalLink',
475
- },
476
- {
477
- document: {_id: 'mock-id'},
478
- parent: {_key: 'block-key'},
479
- path: ['content', {_key: 'block-key'}, 'markDefs', {_key: '1'}],
480
- type: {name: 'internalLink'},
481
- },
482
- ],
483
- ])
484
- })
485
-
486
- it('resolves an array item type if there is just one type', async () => {
487
- const schema = createSchema({
488
- types: [
489
- {
490
- name: 'values',
491
- title: 'Values',
492
- type: 'array',
493
- // note that there is only one type available
494
- of: [{type: 'arrayItem'}],
495
- validation: (rule: Rule) => rule.required(),
496
- },
497
- {
498
- title: 'Array Item',
499
- name: 'arrayItem',
500
- type: 'object',
501
- fields: [{name: 'title', type: 'string'}],
502
- },
503
- ],
504
- })
505
-
506
- // ensures there are no schema formatting issues
507
- expect(schema._validation).toHaveLength(0)
508
-
509
- const values = [
510
- {
511
- // note how this doesn't have a _type
512
- title: 5,
513
- _key: 'exampleKey',
514
- },
515
- ]
516
-
517
- await expect(
518
- validateItem({
519
- getClient,
520
- schema,
521
- document: undefined,
522
- parent: undefined,
523
- path: [],
524
- type: schema.get('values'),
525
- value: values,
526
- getDocumentExists: undefined,
527
- })
528
- ).resolves.toEqual([
529
- {
530
- level: 'error',
531
- item: {
532
- message: 'Expected type "String", got "Number"',
533
- paths: [],
534
- },
535
- path: [{_key: 'exampleKey'}, 'title'],
536
- },
537
- ])
538
- })
539
-
540
- it('properly passes the nested value, type, and path to rule.validate', async () => {
541
- const schema: Schema = createSchema({
542
- types: [
543
- {
544
- name: 'root',
545
- type: 'object',
546
- title: 'Root',
547
- fields: [
548
- {
549
- name: 'level1Object',
550
- type: 'object',
551
- validation: (rule: Rule) => rule.custom(() => 'from level 1 object'),
552
- fields: [
553
- {
554
- name: 'level2String',
555
- type: 'string',
556
- validation: (rule: Rule) => rule.custom(() => 'from level 2 via object'),
557
- },
558
- ],
559
- },
560
- {
561
- name: 'level1Array',
562
- type: 'array',
563
- validation: (rule: Rule) => rule.custom(() => 'from level 1 array'),
564
- of: [
565
- {
566
- type: 'object',
567
- fields: [
568
- {
569
- name: 'level2Number',
570
- type: 'number',
571
- validation: (rule: Rule) => rule.custom(() => 'from level 2 via array'),
572
- },
573
- ],
574
- },
575
- ],
576
- },
577
- ],
578
- validation: (rule: Rule) => rule.custom(() => 'from root'),
579
- },
580
- ],
581
- })
582
-
583
- // ensures there are no schema formatting issues
584
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
585
- expect((schema as any)._validation).toHaveLength(0)
586
-
587
- const value = {
588
- level1Object: {level3String: 'a string'},
589
- level1Array: [{level2Number: 5}],
590
- }
591
-
592
- const document: SanityDocument = {
593
- value,
594
- _type: 'something',
595
- _createdAt: '2021-09-05T19:28:30.882Z',
596
- _id: 'something.id',
597
- _rev: 'exampleRev',
598
- _updatedAt: '2021-09-05T19:28:30.882Z',
599
- }
600
-
601
- const getField = ({in: type, name}: {in: SchemaType; name: string}) => {
602
- const result = 'fields' in type && type.fields.find((f) => f.name === name)?.type
603
- if (!result) throw new Error(`Could not find field \`${name}\` in \`${type.name}\``)
604
- return result
605
- }
606
-
607
- const rootType = schema.get('root')
608
- const level1ObjectType = getField({in: rootType!, name: 'level1Object'})
609
- const level2StringType = getField({in: level1ObjectType, name: 'level2String'})
610
- const level1ArrayType = getField({in: rootType!, name: 'level1Array'})
611
- const level2NumberType = getField({
612
- in: (level1ArrayType as ArraySchemaType).of[0],
613
- name: 'level2Number',
614
- })
615
-
616
- await expect(
617
- validateItem({
618
- getClient,
619
- schema,
620
- value,
621
- type: rootType,
622
- document,
623
- parent: document,
624
- path: undefined,
625
- getDocumentExists: undefined,
626
- })
627
- ).resolves.toMatchObject([
628
- {
629
- item: {message: 'from root'},
630
- path: [],
631
- },
632
- {
633
- item: {message: 'from level 1 object'},
634
- path: ['level1Object'],
635
- },
636
- {
637
- item: {message: 'from level 2 via object'},
638
- path: ['level1Object', 'level2String'],
639
- },
640
- {
641
- item: {message: 'from level 1 array'},
642
- path: ['level1Array'],
643
- },
644
- {
645
- item: {message: 'from level 2 via array'},
646
- path: ['level1Array', 0, 'level2Number'],
647
- },
648
- ])
649
-
650
- const calls = (convertToValidationMarker as jest.Mock).mock.calls
651
-
652
- expect(calls.find((call) => call[0] === 'from root')).toMatchObject([
653
- 'from root',
654
- 'error',
655
- {
656
- parent: document,
657
- document: document,
658
- path: [],
659
- type: rootType,
660
- },
661
- ])
662
- expect(calls.find((call) => call[0] === 'from level 1 object')).toMatchObject([
663
- 'from level 1 object',
664
- 'error',
665
- {
666
- parent: value,
667
- document: document,
668
- path: ['level1Object'],
669
- type: level1ObjectType,
670
- },
671
- ])
672
- expect(calls.find((call) => call[0] === 'from level 2 via object')).toMatchObject([
673
- 'from level 2 via object',
674
- 'error',
675
- {
676
- parent: value.level1Object,
677
- document: document,
678
- path: ['level1Object', 'level2String'],
679
- type: level2StringType,
680
- },
681
- ])
682
- expect(calls.find((call) => call[0] === 'from level 1 array')).toMatchObject([
683
- 'from level 1 array',
684
- 'error',
685
- {
686
- parent: value,
687
- document: document,
688
- path: ['level1Array'],
689
- type: level1ArrayType,
690
- },
691
- ])
692
- expect(calls.find((call) => call[0] === 'from level 2 via array')).toMatchObject([
693
- 'from level 2 via array',
694
- 'error',
695
- {
696
- parent: value.level1Array[0],
697
- document: document,
698
- path: ['level1Array', 0, 'level2Number'],
699
- type: level2NumberType,
700
- },
701
- ])
702
- })
703
- })