forked from Effect-TS/effect
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.ts
More file actions
1833 lines (1776 loc) · 72.4 KB
/
Copy pathschema.ts
File metadata and controls
1833 lines (1776 loc) · 72.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as Effect from "../../Effect.ts"
import * as Equal from "../../Equal.ts"
import { identity } from "../../Function.ts"
import * as Hash from "../../Hash.ts"
import * as Option from "../../Option.ts"
import * as Order from "../../Order.ts"
import * as Schema from "../../Schema.ts"
import * as SchemaAST from "../../SchemaAST.ts"
import * as SchemaGetter from "../../SchemaGetter.ts"
import * as SchemaParser from "../../SchemaParser.ts"
import { effectIsExit } from "../effect.ts"
import { errorWithPath } from "../errors.ts"
import * as InternalRecord from "../record.ts"
import * as Model from "./model.ts"
import * as Regexp from "./regexp.ts"
type FilterConstraint = Schema.Annotations.ToArbitrary.FilterConstraint<any>
type GenerationConstraint = Schema.Annotations.ToArbitrary.GenerationConstraint<any>
interface Checks {
readonly constraint: FilterConstraint | undefined
readonly filters: ReadonlyArray<SchemaAST.Filter<any>>
}
const infinity = Number.POSITIVE_INFINITY
const finiteNumberConstraint: FilterConstraint = { number: "finite" }
const optionMatch = { onFailure: Option.none, onSuccess: Option.some }
const optionComputation = <A, E, R>(self: Effect.Effect<A, E, R>): Model.Computation<Option.Option<A>> => {
const result = Effect.matchEager(self, optionMatch) as Effect.Effect<Option.Option<A>>
return effectIsExit(result) && result._tag === "Success" ? result.value : result
}
/** @internal */
export function compileValidator<S extends Schema.Constraint>(
schema: S
): (value: S["Type"]) => Model.Computation<Option.Option<S["Type"]>> {
const parse = SchemaParser.run<S["Type"], never>(SchemaAST.toType(schema.ast))
return (value) => optionComputation(parse(value))
}
function arbitraryError(what: string, path: ReadonlyArray<PropertyKey>) {
return errorWithPath(`Unable to derive an arbitrary for ${what}`, path)
}
function sumCosts(costs: Iterable<number>): number {
let out = 0
for (const cost of costs) {
if (cost === infinity) return infinity
out += cost
}
return out
}
function mergeOrderedBound<T>(
order: Order.Order<T>,
self: T | undefined,
selfExclusive: boolean | undefined,
that: T | undefined,
thatExclusive: boolean | undefined,
takeComparison: -1 | 1
): readonly [T | undefined, boolean | undefined] {
if (that === undefined || self === undefined) {
return that === undefined ? [self, selfExclusive] : [that, thatExclusive]
}
const comparison = order(self, that)
return comparison === takeComparison
? [that, thatExclusive]
: comparison === 0
? [self, selfExclusive || thatExclusive]
: [self, selfExclusive]
}
function mergeMinimum(self: number | undefined, that: number | undefined): number | undefined {
return self === undefined ? that : that === undefined ? self : Math.max(self, that)
}
function mergeMaximum(self: number | undefined, that: number | undefined): number | undefined {
return self === undefined ? that : that === undefined ? self : Math.min(self, that)
}
function mergeConstraint(self: FilterConstraint | undefined, that: FilterConstraint): FilterConstraint {
const order = that.order ?? self?.order
if (self?.order !== undefined && that.order !== undefined && self.order !== that.order) {
throw new Error("Cannot merge ordered arbitrary constraints with different Order instances")
}
const [minimum, exclusiveMinimum] = order === undefined
? [that.minimum ?? self?.minimum, that.exclusiveMinimum ?? self?.exclusiveMinimum]
: mergeOrderedBound(
order,
self?.minimum,
self?.exclusiveMinimum,
that.minimum,
that.exclusiveMinimum,
-1
)
const [maximum, exclusiveMaximum] = order === undefined
? [that.maximum ?? self?.maximum, that.exclusiveMaximum ?? self?.exclusiveMaximum]
: mergeOrderedBound(
order,
self?.maximum,
self?.exclusiveMaximum,
that.maximum,
that.exclusiveMaximum,
1
)
const minLength = mergeMinimum(self?.minLength, that.minLength)
const maxLength = mergeMaximum(self?.maxLength, that.maxLength)
const minSize = mergeMinimum(self?.minSize, that.minSize)
const maxSize = mergeMaximum(self?.maxSize, that.maxSize)
const minProperties = mergeMinimum(self?.minProperties, that.minProperties)
const maxProperties = mergeMaximum(self?.maxProperties, that.maxProperties)
const patterns = self?.patterns === undefined
? that.patterns
: that.patterns === undefined
? self.patterns
: [...self.patterns, ...that.patterns] as [
Schema.Annotations.ToArbitrary.Pattern,
...Array<Schema.Annotations.ToArbitrary.Pattern>
]
const number = self?.number === "integer" || that.number === "integer"
? "integer"
: self?.number === "finite" || that.number === "finite"
? "finite"
: undefined
const uniqueBy = that.uniqueBy ?? self?.uniqueBy
return {
...(order === undefined ? undefined : { order }),
...(minimum === undefined ? undefined : { minimum }),
...(exclusiveMinimum === true ? { exclusiveMinimum: true } : undefined),
...(maximum === undefined ? undefined : { maximum }),
...(exclusiveMaximum === true ? { exclusiveMaximum: true } : undefined),
...(minLength === undefined ? undefined : { minLength }),
...(maxLength === undefined ? undefined : { maxLength }),
...(minSize === undefined ? undefined : { minSize }),
...(maxSize === undefined ? undefined : { maxSize }),
...(minProperties === undefined ? undefined : { minProperties }),
...(maxProperties === undefined ? undefined : { maxProperties }),
...(patterns === undefined ? undefined : { patterns }),
...(number === undefined ? undefined : { number }),
...(uniqueBy === undefined ? undefined : { uniqueBy })
}
}
function collectChecks(checks: SchemaAST.Checks | undefined, inherited: FilterConstraint | undefined): Checks {
let constraint = inherited
const filters: Array<SchemaAST.Filter<any>> = []
const visit = (check: SchemaAST.Check<any>): void => {
const next = check.annotations?.arbitraryConstraint
if (next !== undefined) constraint = mergeConstraint(constraint, next)
if (check._tag === "Filter") {
filters.push(check)
} else {
check.checks.forEach(visit)
}
}
checks?.forEach(visit)
return { constraint, filters }
}
function applyFilters(
compiled: Model.Compiled<any>,
ast: SchemaAST.AST,
filters: ReadonlyArray<SchemaAST.Filter<any>>
): void {
if (filters.length === 0) return
const generate = compiled.generate
const passes = (value: unknown) => {
for (let index = 0; index < filters.length; index++) {
if (filters[index].run(value, ast, SchemaAST.defaultParseOptions) !== undefined) return false
}
return true
}
compiled.generate = (state) =>
Model.mapGeneration(generate(state), (attempt) => {
if (attempt._tag === "Discarded") return Model.discarded
if (!state.shrinks) return passes(attempt.value) ? attempt : Model.discarded
const sample = Model.filterSample(attempt, passes)
return sample ?? Model.discarded
})
}
function validateConstraint(constraint: FilterConstraint | undefined, path: ReadonlyArray<PropertyKey>): void {
if (constraint === undefined) return
const cardinalities = [
[constraint.minLength, constraint.maxLength],
[constraint.minSize, constraint.maxSize],
[constraint.minProperties, constraint.maxProperties]
] as const
for (const [minimum, maximum] of cardinalities) {
if (
minimum !== undefined && (!Number.isSafeInteger(minimum) || minimum < 0) ||
maximum !== undefined && (!Number.isSafeInteger(maximum) || maximum < 0) ||
minimum !== undefined && maximum !== undefined && minimum > maximum
) {
throw arbitraryError("constraints", path)
}
}
if (constraint.order !== undefined && constraint.minimum !== undefined && constraint.maximum !== undefined) {
const comparison = constraint.order(constraint.minimum, constraint.maximum)
if (
comparison > 0 ||
comparison === 0 && (constraint.exclusiveMinimum === true || constraint.exclusiveMaximum === true)
) {
throw arbitraryError("constraints", path)
}
}
}
function withoutOrder(constraint: FilterConstraint | undefined): GenerationConstraint | undefined {
if (constraint === undefined) return undefined
const { order: _, ...out } = constraint
return Object.keys(out).length === 0 ? undefined : out
}
const minimumDateTimestamp = -8_640_000_000_000_000
const maximumDateTimestamp = 8_640_000_000_000_000
const regexpArbitraryFlags = ["g", "i", "m", "s", "u", "y"] as const
function jsonSchema(): Schema.Codec<Schema.Json> {
let schema: Schema.Codec<Schema.Json>
schema = Schema.Union([
Schema.Null,
Schema.Finite,
Schema.Boolean,
Schema.String,
Schema.Array(Schema.suspend(() => schema)),
Schema.Record(Schema.String, Schema.suspend(() => schema))
]) as Schema.Codec<Schema.Json>
return schema
}
function regexpSchema() {
return Schema.Struct({
source: Schema.Literals([
"",
".",
".*",
"\\d+",
"\\w+",
"[a-z]+",
"[A-Z]+",
"[0-9]+",
"^[a-zA-Z0-9]+$",
"^\\d{4}-\\d{2}-\\d{2}$"
]),
flags: Schema.Struct({
g: Schema.Boolean,
i: Schema.Boolean,
m: Schema.Boolean,
s: Schema.Boolean,
u: Schema.Boolean,
y: Schema.Boolean
})
})
}
function urlSchema() {
return Schema.Struct({
protocol: Schema.Literals(["http", "https"]),
label: Schema.String.check(Schema.isPattern(/^[a-z0-9]+$/), Schema.isMinLength(1), Schema.isMaxLength(63)),
suffix: Schema.String.check(Schema.isPattern(/^[a-z]+$/), Schema.isMinLength(2), Schema.isMaxLength(10)),
path: Schema.Array(
Schema.String.check(Schema.isPattern(/^[A-Za-z0-9._~%-]*$/), Schema.isMaxLength(16))
).check(Schema.isMaxLength(4))
})
}
function dateSchema(constraint: GenerationConstraint | undefined) {
const minimum = Math.max(
minimumDateTimestamp,
constraint?.minimum === undefined
? minimumDateTimestamp
: constraint.minimum.getTime() + (constraint.exclusiveMinimum === true ? 1 : 0)
)
const maximum = Math.min(
maximumDateTimestamp,
constraint?.maximum === undefined
? maximumDateTimestamp
: constraint.maximum.getTime() - (constraint.exclusiveMaximum === true ? 1 : 0)
)
return Schema.Int.check(Schema.isBetween({ minimum, maximum }))
}
const linkToArbitrary = Schema.linkDecoding
function builtInDeclarationLink(
ast: SchemaAST.Declaration,
typeParameters: ReadonlyArray<Schema.Constraint>,
constraint: GenerationConstraint | undefined
): SchemaAST.Link | undefined {
const representation = (ast.annotations as Schema.Annotations.Declaration<any> | undefined)?.representation
if (representation === undefined) return undefined
switch (representation.id) {
case "effect/schema/Json":
return linkToArbitrary<Schema.Json>()(jsonSchema(), SchemaGetter.passthrough())
case "effect/schema/MutableJson":
return linkToArbitrary<Schema.MutableJson>()(
jsonSchema(),
SchemaGetter.passthrough<Schema.MutableJson, Schema.Json>({ strict: false })
)
case "effect/schema/RegExp":
return linkToArbitrary<globalThis.RegExp>()(
regexpSchema(),
SchemaGetter.transform(({ flags, source }) =>
new globalThis.RegExp(source, regexpArbitraryFlags.filter((flag) => flags[flag]).join(""))
)
)
case "effect/schema/URL":
return linkToArbitrary<globalThis.URL>()(
urlSchema(),
SchemaGetter.transform(({ label, path, protocol, suffix }) =>
new globalThis.URL(`${protocol}://${label}.${suffix}/${path.join("/")}`)
)
)
case "effect/schema/Date":
return linkToArbitrary<globalThis.Date>()(dateSchema(constraint), SchemaGetter.Date<number>())
case "effect/schema/ReadonlyMap": {
const [key, value] = typeParameters
return linkToArbitrary<globalThis.ReadonlyMap<unknown, unknown>>()(
Schema.withArrayLengthConstraints(
Schema.Array(Schema.Tuple([key, value])).check(Schema.isUniqueKey()),
constraint?.minSize,
constraint?.maxSize
),
SchemaGetter.transform((entries) => new globalThis.Map(entries))
)
}
case "effect/schema/ReadonlySet":
return linkToArbitrary<globalThis.ReadonlySet<unknown>>()(
Schema.withArrayLengthConstraints(
Schema.Array(typeParameters[0]).check(Schema.isUnique()),
constraint?.minSize,
constraint?.maxSize
),
SchemaGetter.transform((values) => new globalThis.Set(values))
)
case "effect/schema/Uint8Array":
return linkToArbitrary<globalThis.Uint8Array<ArrayBufferLike>>()(
Schema.withArrayLengthConstraints(
Schema.Array(Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 255 }))),
constraint?.minLength,
constraint?.maxLength
),
SchemaGetter.transform<globalThis.Uint8Array<ArrayBufferLike>, ReadonlyArray<number>>((values) =>
globalThis.Uint8Array.from(values)
)
)
default:
return undefined
}
}
function lengthBounds(
constraint: FilterConstraint | undefined,
keys: readonly [
minimum: "minLength" | "minSize" | "minProperties",
maximum: "maxLength" | "maxSize" | "maxProperties"
],
path: ReadonlyArray<PropertyKey>,
label: string
): readonly [minimum: number, maximum: number | undefined] {
const minimum = constraint?.[keys[0]] ?? 0
const maximum = constraint?.[keys[1]]
if (
!Number.isSafeInteger(minimum) || minimum < 0 ||
maximum !== undefined && (!Number.isSafeInteger(maximum) || maximum < minimum)
) {
throw arbitraryError(`${label} constraints`, path)
}
return [minimum, maximum]
}
function constant<A>(value: A): Model.Compiled<A> {
const sample = Model.makeSample(value)
return Model.makeCompiled([], () => 0, () => sample)
}
function replaceAt<A>(values: ReadonlyArray<A>, index: number, value: A): Array<A> {
const out = values.slice()
out[index] = value
return out
}
function arraySample(
children: ReadonlyArray<Model.Sample<any>>,
shape: {
readonly fixedCount: number
readonly optionalCount: number
readonly repeatCount: number
readonly tailCount: number
readonly minimum: number
},
shrinks = true
): Model.Sample<ReadonlyArray<any>> {
if (!shrinks) return Model.makeSample(children.map((child) => child.value))
const product = Model.productSample(
children,
(children) => children.map((child) => child.value),
(children) => arraySample(children, shape)
)
// Like fast-check v4.9.0's ArrayArbitrary (MIT), structural shrinks are tried before element shrinks.
// https://github.com/dubzzz/fast-check/blob/v4.9.0/packages/fast-check/src/arbitrary/_internals/ArrayArbitrary.ts
const structural: Array<() => Model.Sample<ReadonlyArray<any>>> = []
if (shape.repeatCount > 0 && children.length - 1 >= shape.minimum) {
const index = shape.fixedCount + shape.repeatCount - 1
structural.push(() =>
arraySample(children.slice(0, index).concat(children.slice(index + 1)), {
...shape,
repeatCount: shape.repeatCount - 1
})
)
} else if (
shape.optionalCount > 0 && shape.repeatCount === 0 && shape.tailCount === 0 &&
children.length - 1 >= shape.minimum
) {
structural.push(() =>
arraySample(children.slice(0, -1), {
...shape,
fixedCount: shape.fixedCount - 1,
optionalCount: shape.optionalCount - 1
})
)
}
if (structural.length === 0) return product
const structuralPull = Effect.map(Model.pullFromArray(structural), (make) => make())
return Model.makeSample(
product.value,
product.shrinks === undefined ? structuralPull : Model.concatPulls([structuralPull, product.shrinks])
)
}
interface ObjectEntry {
readonly key: PropertyKey
readonly keySample?: Model.Sample<PropertyKey> | undefined
readonly sample: Model.Sample<any>
readonly removable: boolean
}
function normalizePropertyKeySample(sample: Model.Sample<any>): Model.Sample<PropertyKey> | undefined {
const filtered = Model.filterSample(
sample,
(value): value is string | number | symbol =>
typeof value === "string" || typeof value === "number" || typeof value === "symbol"
)
return filtered === undefined
? undefined
: Model.mapSample(filtered, (value) => typeof value === "symbol" ? value : globalThis.String(value))
}
function objectSample(
entries: ReadonlyArray<ObjectEntry>,
minimum: number,
nullPrototype: boolean,
shrinks = true
): Model.Sample<Record<PropertyKey, any>> {
const make = (entries: ReadonlyArray<ObjectEntry>) => {
const out = Model.makeObject(nullPrototype)
for (const entry of entries) InternalRecord.assignProperty(out, entry.key, entry.sample.value)
return out
}
if (!shrinks) return Model.makeSample(make(entries))
const childPulls = entries.flatMap((entry, index) =>
entry.sample.shrinks === undefined
? []
: [
Effect.map(
entry.sample.shrinks,
(attempt) =>
Model.mapAttempt(
attempt,
(sample) => objectSample(replaceAt(entries, index, { ...entry, sample }), minimum, nullPrototype)
)
)
]
)
// Key shrinking uses the same uniqueness-preserving descendant filtering principle as fast-check v4.9.0's
// ArrayArbitrary (MIT). Structural removals and value shrinks retain their established precedence.
// https://github.com/dubzzz/fast-check/blob/v4.9.0/packages/fast-check/src/arbitrary/_internals/ArrayArbitrary.ts
const keyPulls = entries.flatMap((entry, index) => {
if (entry.keySample === undefined || entry.keySample.shrinks === undefined) return []
const filtered = Model.filterSample(
entry.keySample,
(key) => !entries.some((other, otherIndex) => otherIndex !== index && other.key === key)
)
if (filtered?.shrinks === undefined) return []
return [Effect.map(
filtered.shrinks,
(attempt) =>
Model.mapAttempt(
attempt,
(keySample) =>
objectSample(
replaceAt(entries, index, { ...entry, key: keySample.value, keySample }),
minimum,
nullPrototype
)
)
)]
})
const structural: Array<() => Model.Sample<Record<PropertyKey, any>>> = entries.length <= minimum
? []
: entries.flatMap((entry, index) =>
entry.removable
? [() => objectSample(entries.slice(0, index).concat(entries.slice(index + 1)), minimum, nullPrototype)]
: []
)
const descendantPulls = [...childPulls, ...keyPulls]
const pulls = structural.length === 0
? descendantPulls
: [Effect.map(Model.pullFromArray(structural), (make) => make()), ...descendantPulls]
return Model.makeSample(make(entries), pulls.length === 0 ? undefined : Model.concatPulls(pulls))
}
const generateSamples = (
children: ReadonlyArray<Model.Compiled<any>>,
state: Model.GenerationState,
additionalReserved = 0
): Model.Computation<Array<Model.Sample<any>> | undefined> => {
let reserved = additionalReserved
let recursive: Array<number> | undefined
for (let index = 0; index < children.length; index++) {
const child = children[index]
if (reserved !== infinity) reserved += child.minCost
if (child.mayRecurse) (recursive ??= []).push(index)
}
if (reserved > state.budget.remaining) return undefined
let order: Array<number> | undefined
if (recursive !== undefined && recursive.length > 1) {
order = children.map((_, index) => index)
const shuffled = Model.shuffle(state, recursive)
let next = 0
for (let index = 0; index < order.length; index++) {
if (children[index].mayRecurse) order[index] = shuffled[next++]
}
}
return Model.generateProduct(children, state, order, reserved)
}
const generateRequiredObjectValues = (
properties: ReadonlyArray<{
readonly property: { readonly name: PropertyKey }
readonly compiled: Model.Compiled<any>
}>,
state: Model.GenerationState,
nullPrototype: boolean
): Model.Generation<Record<PropertyKey, any>> => {
let reserved = 0
let recursive: Array<number> | undefined
for (let index = 0; index < properties.length; index++) {
const child = properties[index].compiled
if (reserved !== infinity) reserved += child.minCost
if (child.mayRecurse) (recursive ??= []).push(index)
}
if (reserved > state.budget.remaining) return Model.discarded
let order: Array<number> | undefined
if (recursive !== undefined && recursive.length > 1) {
order = properties.map((_, index) => index)
const shuffled = Model.shuffle(state, recursive)
let next = 0
for (let index = 0; index < order.length; index++) {
if (properties[index].compiled.mayRecurse) order[index] = shuffled[next++]
}
}
const values = new Array<any>(properties.length)
let index = 0
const loop = (): Model.Generation<Record<PropertyKey, any>> => {
while (index < properties.length) {
const childIndex = order?.[index] ?? index
index++
const child = properties[childIndex]
reserved -= child.compiled.minCost
const generated = Model.generateWithReservedBudget(child.compiled, state, reserved)
if (Model.isAttempt(generated)) {
if (generated._tag === "Discarded") return Model.discarded
values[childIndex] = generated.value
continue
}
return Effect.flatMapEager(generated, (attempt) => {
if (attempt._tag === "Discarded") return Effect.succeed(Model.discarded)
values[childIndex] = attempt.value
return Model.toEffectGeneration(loop())
})
}
const out = Model.makeObject(nullPrototype)
for (let index = 0; index < properties.length; index++) {
InternalRecord.assignProperty(out, properties[index].property.name, values[index])
}
return Model.makeSample(out)
}
return loop()
}
const generateRepeatedValues = (
child: Model.Compiled<any>,
count: number,
state: Model.GenerationState
): Model.Generation<ReadonlyArray<any>> => {
// The packed push loop follows fast-check v4.9.0's ArrayArbitrary generation strategy (MIT).
// https://github.com/dubzzz/fast-check/blob/v4.9.0/packages/fast-check/src/arbitrary/_internals/ArrayArbitrary.ts
const out: Array<any> = []
let remaining = count
let reserved = count * child.minCost
const loop = (): Model.Generation<ReadonlyArray<any>> => {
while (remaining > 0) {
reserved -= child.minCost
const generated = Model.generateWithReservedBudget(child, state, reserved)
if (Model.isAttempt(generated)) {
if (generated._tag === "Discarded") return Model.discarded
out.push(generated.value)
remaining--
continue
}
return Effect.flatMapEager(generated, (attempt) => {
if (attempt._tag === "Discarded") return Effect.succeed(Model.discarded)
out.push(attempt.value)
remaining--
return Model.toEffectGeneration(loop())
})
}
return Model.makeSample(out)
}
return loop()
}
const generateRepeatedRecursiveValues = (
child: Model.Compiled<any>,
count: number,
state: Model.GenerationState
): Model.Generation<ReadonlyArray<any>> => {
const out = new Array<any>(count)
const order = Model.shuffle(state, Array.from({ length: count }, (_, index) => index))
let index = 0
let reserved = count * child.minCost
const loop = (): Model.Generation<ReadonlyArray<any>> => {
while (index < count) {
reserved -= child.minCost
const generated = Model.generateWithReservedBudget(child, state, reserved)
if (Model.isAttempt(generated)) {
if (generated._tag === "Discarded") return Model.discarded
out[order[index++]] = generated.value
continue
}
return Effect.flatMapEager(generated, (attempt) => {
if (attempt._tag === "Discarded") return Effect.succeed(Model.discarded)
out[order[index++]] = attempt.value
return Model.toEffectGeneration(loop())
})
}
return Model.makeSample(out)
}
return loop()
}
// Selector-based uniqueness and primitive Set tracking follow fast-check v4.9.0's uniqueArray and SameValueSet
// strategies (MIT). Hash buckets extend them with Effect's equality semantics for objects.
// https://github.com/dubzzz/fast-check/blob/v4.9.0/packages/fast-check/src/arbitrary/uniqueArray.ts
// https://github.com/dubzzz/fast-check/blob/v4.9.0/packages/fast-check/src/arbitrary/_internals/helpers/SameValueSet.ts
const makeUniqueAdder = (): (value: any) => boolean => {
let primitives: Set<any> | undefined
let buckets: Map<number, Array<any>> | undefined
return (value) => {
if (value === null || typeof value !== "object" && typeof value !== "function") {
const set = primitives ??= new Set()
const size = set.size
set.add(value)
return set.size !== size
}
const hash = Hash.hash(value)
const map = buckets ??= new Map()
const bucket = map.get(hash)
if (bucket !== undefined) {
for (let index = 0; index < bucket.length; index++) {
if (Equal.equals(bucket[index], value)) return false
}
bucket.push(value)
} else {
map.set(hash, [value])
}
return true
}
}
const makeUniqueAdderBy = (
uniqueBy: (value: any) => unknown
): (value: any) => boolean => {
const add = makeUniqueAdder()
return uniqueBy === identity ? add : (input) => add(uniqueBy(input))
}
const generateRepeatedUniqueValues = (
child: Model.Compiled<any>,
count: number,
state: Model.GenerationState,
uniqueBy: (value: any) => unknown
): Model.Generation<ReadonlyArray<any>> => {
const out: Array<any> = []
const addUnique = makeUniqueAdderBy(uniqueBy)
let remaining = count
let reserved = count * child.minCost
let retries = 0
let budget = state.budget.remaining
const loop = (): Model.Generation<ReadonlyArray<any>> => {
while (remaining > 0) {
if (retries === 0) {
reserved -= child.minCost
budget = state.budget.remaining
}
const generated = Model.generateWithReservedBudget(child, state, reserved)
if (Model.isAttempt(generated)) {
if (generated._tag === "Discarded") return Model.discarded
if (!addUnique(generated.value)) {
if (++retries >= count) return Model.discarded
state.budget.remaining = budget
continue
}
out.push(generated.value)
remaining--
retries = 0
continue
}
return Effect.flatMapEager(generated, (attempt) => {
if (attempt._tag === "Discarded") return Effect.succeed(Model.discarded)
if (!addUnique(attempt.value)) {
if (++retries >= count) return Effect.succeed(Model.discarded)
state.budget.remaining = budget
} else {
out.push(attempt.value)
remaining--
retries = 0
}
return Model.toEffectGeneration(loop())
})
}
return Model.makeSample(out)
}
return loop()
}
function shrinkString(value: string, minimum: number): ReadonlyArray<string> {
const values = value.length <= minimum
? []
: [
value.slice(0, minimum),
value.slice(0, Math.max(minimum, Math.floor(value.length / 2))),
value.slice(0, -1)
]
// fast-check v4.9.0 builds strings from shrinkable units (MIT). Effect keeps UTF-16 code units as its string domain
// and applies its integer-halving shrink toward the Effect-owned null-unit target.
// https://github.com/dubzzz/fast-check/blob/v4.9.0/packages/fast-check/src/arbitrary/string.ts
for (let index = 0; index < value.length; index++) {
for (const candidate of shrinkInteger(value.charCodeAt(index), 0, true)) {
values.push(
value.slice(0, index) + globalThis.String.fromCharCode(candidate.value) + value.slice(index + 1)
)
}
}
return [...new Set(values)].filter((candidate) => candidate !== value)
}
// Edge-case injection is inspired by fast-check v4.9.0's cached dangerous slices (MIT). The concrete corpus is
// Effect-owned and also covers control, numeric-property, and UTF-16 boundaries.
// https://github.com/dubzzz/fast-check/blob/v4.9.0/packages/fast-check/src/arbitrary/_internals/helpers/SlicesForStringBuilder.ts
const stringEdgeCases = [
"",
" ",
"\t",
"\n",
"\0",
"0",
"-1",
"4294967295",
"__proto__",
"constructor",
"prototype",
"toString",
"\uD800",
"\uDC00",
"😀"
] as const
function randomString(state: Model.GenerationState, minimum: number, maximum: number): string {
if (Model.randomInt(state, 1, state.biasFactor) === 1) {
let eligible = 0
for (const value of stringEdgeCases) {
if (value.length >= minimum && value.length <= maximum) eligible++
}
if (eligible > 0) {
let target = Model.randomIndex(state, eligible)
for (const value of stringEdgeCases) {
if (value.length < minimum || value.length > maximum) continue
if (target-- === 0) return value
}
}
}
const length = Model.randomLength(state, minimum, maximum)
let value = ""
for (let index = 0; index < length; index++) {
value += globalThis.String.fromCharCode(Model.randomInt(state, 32, 126))
}
return value
}
function numberBounds(constraint: FilterConstraint | undefined, integer: boolean, path: ReadonlyArray<PropertyKey>) {
const ordered = constraint?.order === Order.Number ? constraint : undefined
let minimum = ordered?.minimum as number | undefined
let maximum = ordered?.maximum as number | undefined
if (minimum !== undefined && Number.isNaN(minimum) || maximum !== undefined && Number.isNaN(maximum)) {
throw arbitraryError(integer ? "integer constraints" : "number constraints", path)
}
if (integer) {
if (minimum !== undefined) {
minimum = ordered?.exclusiveMinimum === true
? Math.floor(minimum) + 1
: Math.ceil(minimum)
}
if (maximum !== undefined) {
maximum = ordered?.exclusiveMaximum === true
? Math.ceil(maximum) - 1
: Math.floor(maximum)
}
} else {
if (minimum !== undefined && ordered?.exclusiveMinimum === true && minimum === Infinity) {
throw arbitraryError("number constraints", path)
}
if (maximum !== undefined && ordered?.exclusiveMaximum === true && maximum === -Infinity) {
throw arbitraryError("number constraints", path)
}
if (minimum !== undefined) {
minimum = ordered?.exclusiveMinimum === true ? Model.nextNumber(minimum) : minimum === 0 ? -0 : minimum
}
if (maximum !== undefined) {
maximum = ordered?.exclusiveMaximum === true ? Model.previousNumber(maximum) : maximum === 0 ? 0 : maximum
}
}
if (integer || constraint?.number === "finite") {
if (minimum === Infinity || maximum === -Infinity) {
throw arbitraryError(integer ? "integer constraints" : "number constraints", path)
}
if (minimum === -Infinity) minimum = integer ? Number.MIN_SAFE_INTEGER : -Number.MAX_VALUE
if (maximum === Infinity) maximum = integer ? Number.MAX_SAFE_INTEGER : Number.MAX_VALUE
}
if (integer) {
if (
minimum !== undefined && minimum > Number.MAX_SAFE_INTEGER ||
maximum !== undefined && maximum < Number.MIN_SAFE_INTEGER
) {
throw arbitraryError("integer constraints", path)
}
if (minimum !== undefined) minimum = Math.max(minimum, Number.MIN_SAFE_INTEGER)
if (maximum !== undefined) maximum = Math.min(maximum, Number.MAX_SAFE_INTEGER)
}
if (
minimum !== undefined && maximum !== undefined &&
(integer ? minimum > maximum : Model.numberToIndex(minimum) > Model.numberToIndex(maximum))
) {
throw arbitraryError(integer ? "integer constraints" : "number constraints", path)
}
return { minimum, maximum }
}
interface NumberShrink {
readonly value: number
readonly context: number | undefined
}
function shrinkInteger(current: number, target: number, tryTargetAsap: boolean): ReadonlyArray<NumberShrink> {
const out: Array<NumberShrink> = []
const realGap = current - target
let previous = tryTargetAsap ? undefined : target
for (
let toRemove = tryTargetAsap ? realGap : Math.trunc(realGap / 2);
toRemove !== 0;
toRemove = Math.trunc(toRemove / 2)
) {
const value = toRemove === realGap ? target : current - toRemove
out.push({ value, context: previous })
previous = value
}
return out
}
function shrinkNumber(current: number, target: number, tryTargetAsap: boolean): ReadonlyArray<NumberShrink> {
if (Number.isNaN(current)) return [{ value: target, context: undefined }]
const currentIndex = Model.numberToIndex(current)
const targetIndex = Model.numberToIndex(target)
const realGap = currentIndex - targetIndex
let previous = tryTargetAsap ? undefined : target
const out: Array<NumberShrink> = []
for (
let toRemove = tryTargetAsap ? realGap : realGap / BigInt(2);
toRemove !== BigInt(0);
toRemove /= BigInt(2)
) {
const value = toRemove === realGap ? target : Model.indexToNumber(currentIndex - toRemove)
out.push({ value, context: previous })
previous = value
}
return out
}
function numberTarget(minimum: number | undefined, maximum: number | undefined): number {
if (minimum !== undefined && minimum > 0) return minimum
if (maximum !== undefined && maximum < 0) return maximum
return 0
}
function numberSample(
value: number,
minimum: number | undefined,
maximum: number | undefined,
integer: boolean,
context?: number
): Model.Sample<number> {
if (!integer) {
// fast-check v4.9.0's double arbitrary shrinks the monotone IEEE-754 index through its BigInt arbitrary (MIT).
// The sample keeps the equivalent last-passing index context without exposing either representation.
// https://github.com/dubzzz/fast-check/blob/v4.9.0/packages/fast-check/src/arbitrary/double.ts
let candidates: ReadonlyArray<NumberShrink>
const target = numberTarget(minimum, maximum)
if (context === undefined) {
candidates = shrinkNumber(value, target, true)
} else if (
!Number.isNaN(value) &&
(Model.numberToIndex(value) === Model.numberToIndex(context) + BigInt(1) ||
Model.numberToIndex(value) === Model.numberToIndex(context) - BigInt(1))
) {
candidates = [{ value: context, context: undefined }]
} else {
candidates = shrinkNumber(value, context, false)
}
return Model.makeSample(
value,
candidates.length === 0
? undefined
: Effect.map(
Model.pullFromArray(candidates),
(candidate) => numberSample(candidate.value, minimum, maximum, false, candidate.context)
)
)
}
// The passing-value context and halving sequence are adapted from fast-check v4.9.0's IntegerArbitrary and
// ShrinkInteger (MIT). Retaining the closest passing candidate lets the runner converge on a local failure boundary.
// https://github.com/dubzzz/fast-check/blob/v4.9.0/packages/fast-check/src/arbitrary/_internals/IntegerArbitrary.ts
// https://github.com/dubzzz/fast-check/blob/v4.9.0/packages/fast-check/src/arbitrary/_internals/helpers/ShrinkInteger.ts
let candidates: ReadonlyArray<NumberShrink>
if (context === undefined) {
const target = Math.min(maximum ?? 0, Math.max(minimum ?? 0, 0))
candidates = shrinkInteger(value, target, true)
} else if (
value > 0 && value === context + 1 && (minimum === undefined || value > minimum) ||
value < 0 && value === context - 1 && (maximum === undefined || value < maximum)
) {
candidates = [{ value: context, context: undefined }]
} else {
candidates = shrinkInteger(value, context, false)
}
return Model.makeSample(
value,
candidates.length === 0
? undefined
: Effect.map(
Model.pullFromArray(candidates),
(candidate) => numberSample(candidate.value, minimum, maximum, true, candidate.context)
)
)
}
function bigIntGenerator(
minimum: bigint | undefined,
maximum: bigint | undefined
): (state: Model.GenerationState) => bigint {
if (minimum !== undefined && maximum !== undefined) return Model.makeRandomNumericBigInt(minimum, maximum)
const zero = BigInt(0)
const center = minimum !== undefined && minimum > zero
? minimum
: maximum !== undefined && maximum < zero
? maximum
: zero
// A single wide uniform interval would almost always produce huge values. Mix magnitude ranges instead,
// independently of collection size, and cap default coefficient widths rather than attempting an infinite range.
const radii = [
BigInt(1),
BigInt(100),
BigInt(1_000_000),
...[53, 64, 256, 1024, 2048].map((bits) => (BigInt(1) << BigInt(bits)) - BigInt(1))
]
const generators = radii.map((radius) =>
Model.makeRandomNumericBigInt(
minimum !== undefined && minimum > center - radius ? minimum : center - radius,
maximum !== undefined && maximum < center + radius ? maximum : center + radius
)
)
// A bound on the far side of zero may lie outside every default range. Still exercise that explicit boundary.
if (minimum !== undefined && minimum < zero) {
generators.push(Model.makeRandomNumericBigInt(minimum, minimum + BigInt(100)))
} else if (maximum !== undefined && maximum > zero) {
generators.push(Model.makeRandomNumericBigInt(maximum - BigInt(100), maximum))
}
return (state) => generators[Model.randomIndex(state, generators.length)](state)