unknown

it('ensureTrailing endsWith', () => {
    fc.assert(fc.property(
      fc.string(),
      fc.string(),
      (s, suffix) => Strings.endsWith(Strings.ensureTrailing(s, suffix), suffix)
    ));
  })

Summary: `Strings.ensureTrailing` ensures that a string ends with a specified suffix by verifying that the result satisfies `Strings.endsWith`.


it('startsWith a prefix', () => {
    fc.assert(fc.property(fc.string(), fc.string(),
      (prefix, suffix) => Strings.startsWith(prefix + suffix, prefix)
    ));
  })

Summary: Concatenating a prefix with a suffix should result in a string that starts with the prefix.


it('A string added to a string (at the end) must have endsWith as true', () => {
    fc.assert(fc.property(
      fc.asciiString(),
      fc.asciiString(),
      (str, contents) => Strings.endsWith(str + contents, contents)
    ));
  })

Summary: Appending a string to another string should result in `endsWith` returning true for the appended string.


it('A string with length 1 or larger should never be empty', () => {
    fc.assert(fc.property(fc.string(1, 40), (str) => {
      assert.isFalse(Strings.isEmpty(str));
      assert.isTrue(Strings.isNotEmpty(str));
    }));
  })

Summary: A string with length of 1 or more should never be considered empty, and `Strings.isEmpty` should return false while `Strings.isNotEmpty` should return true for such strings.


it('A string added to a string (at the end) must be contained within it', () => {
    fc.assert(fc.property(
      fc.string(),
      fc.string(1, 40),
      (str, contents) => {
        const r = str + contents;
        assert.isTrue(Strings.contains(r, contents));
      }
    ));
  })

Summary: Concatenating a string to another string at the end should result in the second string being contained within the concatenated result.


it('A string added to a string (at the start) must be contained within it', () => {
    fc.assert(fc.property(
      fc.string(),
      fc.string(1, 40),
      (str, contents) => {
        const r = contents = str;
        assert.isTrue(Strings.contains(r, contents));
      }
    ));
  })

Summary: A string appended to the start of another string should be recognized as contained within it.


it('should be able to compute a dependency tree for any package of the registry', async () => {
    await fc.assert(
      fc.asyncProperty(AllPackagesArbitrary, fc.scheduler(), async (packages, s) => {
        // Arrange
        const selectedPackage = Object.keys(packages)[0];
        const fetch: (name: string) => Promise<PackageDefinition> = s.scheduleFunction(function fetch(packageName) {
          return Promise.resolve(packages[packageName]);
        });

        // Act
        dependencyTree(selectedPackage, fetch); // without bugs
        // dependencyTree(selectedPackage, fetch, true); // or with bugs

        // Assert
        let numQueries = 0;
        while (s.count() !== 0) {
          if (++numQueries > 2 * Object.keys(packages).length) {
            throw new Error(`Too many queries`);
          }
          await s.waitOne();
        }
      }),
    );
  })

Summary: The function `dependencyTree` should correctly compute a dependency tree for any package from a given registry, ensuring the number of queries does not exceed twice the number of packages.


it('head is uppercase', () => {
    fc.assert(fc.property(fc.ascii(), fc.asciiString(30), (h, t) => {
      const actualH = Strings.capitalize(h + t).charAt(0);
      assert.equal(actualH, h.toUpperCase());
    }));
  })

Summary: `Strings.capitalize` should transform the first character of a string to uppercase.


it('someIf(false) is none', () => {
    fc.assert(fc.property(fc.integer(), (n) => {
      assertNone(Optionals.someIf<number>(false, n));
    }));
  })

Summary: `Optionals.someIf<number>(false, n)` should always return none.


it('someIf(true) is some', () => {
    fc.assert(fc.property(fc.integer(), (n) => {
      assertSome(Optionals.someIf<number>(true, n), n);
    }));
  })

Summary: `Optionals.someIf` returns a 'some' containing the given number when the condition is true.


it('delta is max', () => {
    fc.assert(fc.property(fc.nat(), fc.nat(), (value, delta) => {
      const max = value + delta;
      const actual = Num.cycleBy(value, delta, value, max);
      assert.equal(actual, max);
    }));
  })

Summary: `Num.cycleBy` should return `max` when the initial and maximum values are respectively `value` and `value + delta`.


it('Num.clamp', () => {
    fc.assert(fc.property(
      fc.nat(1000),
      fc.nat(1000),
      fc.nat(1000),
      (a, b, c) => {
        const low = a;
        const med = low + b;
        const high = med + c;
        // low <= med <= high
        assert.equal(Num.clamp(med, low, high), med);
        assert.equal(Num.clamp(med, low, high), med);
        assert.equal(Num.clamp(high, low, med), med);
      }));
  })

Summary: `Num.clamp` returns the middle value when tested with constraints `low <= med <= high` and ensures bounds are maintained.


it('allows creating "Just" maybes', () => {
    fc.assert(fc.property(fc.anything(), (thing) => {
      const item = Maybes.just(thing);
      assert.isTrue(Maybes.isJust(item));
      assert.isFalse(Maybes.isNothing(item));
    }));
  })

Summary: Creating a "Just" maybe with any input should result in `isJust` returning true and `isNothing` returning false.


it('should handle BigInt with maxSafeInteger', () => {
      return fc.assert(
        fc.property(
          fc.maxSafeInteger().map(value => [BigInt(value), value]),
          ([value, expectedValue]) => {
            const stats = {
              [rawField]: value
            }

            const queryStatistics = new QueryStatistics(stats)

            return queryStatistics.updates()[field] === expectedValue
          }
        )
      )
    })

Summary: `QueryStatistics` updates should return the expected numeric value when initialized with a `BigInt` within the `maxSafeInteger` range.


it('allows folding on "Just" maybes', () => {
    // Simple value, complex assertions
    Fun.pipe(
      Maybes.just('test'),
      Maybes.fold(
        Fun.die('Should call other branch'),
        (test) => {
          assert.equal(test, 'test');
          return 'other-test';
        }
      ),
      (result) => assert.equal(result, 'other-test')
    );

    // Complex values, simple assertions
    fc.assert(fc.property(fc.anything(), (thing) => {
      Fun.pipe(
        Maybes.just(thing),
        Maybes.fold(Fun.die('Should call other branch'), Fun.noop)
      );
    }));
  })

Summary: Folding on "Just" instances should result in calling the function associated with the "Just" branch, leading to expected outcomes.


it('gets the value on "Just"', () => {
      fc.assert(fc.property(fc.string(), (s) => {
        const val = Fun.pipe(
          Maybes.just(s),
          Maybes.getOrDie
        );
        assert.equal(val, s);
      }));
    })

Summary: `Maybes.getOrDie` retrieves the value from a `Just` instance correctly, matching the original string.


it('never turns Just to Nothing (or vice versa)', () => {
    const mapper = Maybes.map(Fun.identity);

    const nothing = mapper(Maybes.nothing());
    assert.isTrue(Maybes.isNothing(nothing));

    fc.assert(fc.property(fc.anything(), (thing) => {
      const just = mapper(Maybes.just(thing));
      assert.isTrue(Maybes.isJust(just));
    }));
  })

Summary: Mapping with the identity function retains the original `Just` or `Nothing` state in a `Maybe`.


it('is correct for "Just"', () => {
      fc.assert(fc.property(fc.string(), (thing) => {
        const matches = Fun.pipe(
          Maybes.just(thing),
          Maybes.is(thing)
        );

        assert.isTrue(matches);
      }));

      fc.assert(fc.property(fc.string(), (thing) => {
        const matches = Fun.pipe(
          Maybes.just(thing),
          Maybes.is(thing + 'foo')
        );

        assert.isFalse(matches);
      }));
    })

Summary: `Maybes.is` returns true for a `Just` containing a value matching the input, and false otherwise.


it('compares normally for two "Just"s', () => {
      const different = fc.tuple(fc.anything(), fc.anything()).filter(([ lhs, rhs ]) => lhs !== rhs);
      fc.assert(fc.property(different, ([ lhs, rhs ]) => {
        assert.isFalse(Maybes.equals(Maybes.just(lhs), Maybes.just(rhs)));
      }));

      const theSame = fc.string().map((x) => [ x, x ]);
      fc.assert(fc.property(theSame, ([ lhs, rhs ]) => {
        assert.isTrue(Maybes.equals(Maybes.just(lhs), Maybes.just(rhs)));
      }));
    })

Summary: `Maybes.equals` returns false for different `Just` values and true for identical `Just` values.


Summary: `Maybes.equals` returns false for two `Just` objects with different values and true for two `Just` objects with the same value.


it('is false for one "Nothing"', () => {
      fc.assert(fc.property(fc.anything(), (thing) => {
        assert.isFalse(Maybes.equals(Maybes.nothing(), Maybes.just(thing), unusedComparator));
        assert.isFalse(Maybes.equals(Maybes.just(thing), Maybes.nothing(), unusedComparator));
      }));
    })

Summary: `Maybes.equals` returns false when comparing a `Nothing` with a `Just` of any value.


it('Thunk.cached counter', () => {
    fc.assert(fc.property(fc.json(), fc.func(fc.json()), fc.json(), (a, f, b) => {
      let counter = 0;
      const thunk = Thunk.cached((x) => {
        counter++;
        return {
          counter,
          output: f(x)
        };
      });
      const value = thunk(a);
      const other = thunk(b);
      assert.deepEqual(other, value);
    }));
  })

Summary: `Thunk.cached` ensures that the function invocation count remains identical for subsequent inputs, confirming consistent output from a cached function call.


it('Check compose :: compose(f, g)(x) = f(g(x))', () => {
    fc.assert(fc.property(fc.string(), fc.func(fc.string()), fc.func(fc.string()), (x, f, g) => {
      const h = Fun.compose(f, g);
      assert.deepEqual(h(x), f(g(x)));
    }));
  })

Summary: The composition of two functions `f` and `g` applied to a value `x` should equal applying `f` to the result of `g(x)`.


it('Check compose1 :: compose1(f, g)(x) = f(g(x))', () => {
    fc.assert(fc.property(fc.string(), fc.func(fc.string()), fc.func(fc.string()), (x, f, g) => {
      const h = Fun.compose1(f, g);
      assert.deepEqual(h(x), f(g(x)));
    }));
  })

Summary: `compose1` applies two functions sequentially such that `compose1(f, g)(x)` equals `f(g(x))`.


it('Check never :: f(x) === false', () => {
    fc.assert(fc.property(fc.json(), (json) => {
      assert.isFalse(Fun.never(json));
    }));
  })

Summary: `Fun.never` should return false for any given JSON input.


it('Check not :: not(f(x)) === !f(x)', () => {
    fc.assert(fc.property(fc.json(), fc.func(fc.boolean()), (x, f) => {
      const g = Fun.not(f);
      assert.deepEqual(!g(x), f(x));
    }));
  })

Summary: The `Fun.not` function transforms `f(x)` such that `not(f(x))` equals `!f(x)`, ensuring logical negation is applied correctly.


it('Check not :: not(not(f(x))) === f(x)', () => {
    fc.assert(fc.property(fc.json(), fc.func(fc.boolean()), (x, f) => {
      const g = Fun.not(Fun.not(f));
      assert.deepEqual(g(x), f(x));
    }));
  })

Summary: Applying `not` twice to a function should return the original function's result for any input.


it('Check call :: apply(constant(a)) === undefined', () => {
    fc.assert(fc.property(fc.json(), (x) => {
      let hack: any = null;
      const output = Fun.call(() => {
        hack = x;
      });

      assert.isUndefined(output);
      assert.deepEqual(hack, x);
    }));
  })

Summary: The function `Fun.call` should return `undefined`, while executing a callback that assigns its argument to a variable, which should then match the input JSON.


it('Check that the total number of values and errors matches the input size', () => {
    fc.assert(fc.property(
      fc.array(arbResult(fc.integer(), fc.string())),
      (results) => {
        const actual = Results.partition(results);
        assert.equal(actual.errors.length + actual.values.length, results.length);
      }
    ));
  })

Summary: The total number of partitioned values and errors should equal the input size from `Results.partition`.


it('Check that two errors always equal comparison.bothErrors', () => {
    fc.assert(fc.property(
      arbResultError(fc.integer()),
      arbResultError(fc.integer()),
      (r1, r2) => {
        const comparison = Results.compare(r1, r2);
        return comparison.match({
          bothErrors: Fun.always,
          firstError: Fun.never,
          secondError: Fun.never,
          bothValues: Fun.never
        });
      }
    ));
  })

Summary: Comparing two error results should always yield `comparison.bothErrors` in `Results.compare`.


it('Check that value, error always equal comparison.secondError', () => {
    fc.assert(fc.property(
      arbResultValue(fc.integer()),
      arbResultError(fc.string()),
      (r1, r2) => {
        const comparison = Results.compare(r1, r2);
        return comparison.match({
          bothErrors: Fun.never,
          firstError: Fun.never,
          secondError: Fun.always,
          bothValues: Fun.never
        });
      }
    ));
  })

Summary: The comparison between two results should always match the condition where the second result is an error.


it('Check that value, value always equal comparison.bothValues', () => {
    fc.assert(fc.property(
      arbResultValue(fc.integer()),
      arbResultValue(fc.integer()),
      (r1, r2) => {
        const comparison = Results.compare(r1, r2);
        return comparison.match({
          bothErrors: Fun.never,
          firstError: Fun.never,
          secondError: Fun.never,
          bothValues: Fun.always
        });
      }
    ));
  })

Summary: `Results.compare` should result in `bothValues` when comparing two valid `Result` values.


it('Results.unite', () => {
    fc.assert(fc.property(fc.integer(), (a) => {
      assert.equal(Results.unite(Result.error<number, number>(a)), a);
      assert.equal(Results.unite(Result.value<number, number>(a)), a);
    }));
  })

Summary: `Results.unite` returns the integer value contained in both `Result.error` and `Result.value`.


it('Checking value.is(value.getOrDie()) === true', () => {
    fc.assert(fc.property(arbResultValue(fc.integer()), (res) => {
      assert.isTrue(Results.is(res, res.getOrDie()));
    }));
  })

Summary: `Results.is` should return true for a result when comparing it with the value obtained via `getOrDie()`.


it('should handle concurrent calls to "inc"', async () => {
    await fc.assert(
      fc.asyncProperty(fc.scheduler(), fc.nat(64), async (s, numCalls) => {
        // Arrange
        let dbValue = 0;
        const db = {
          read: s.scheduleFunction(async function read() {
            return dbValue;
          }),
          write: s.scheduleFunction(async function write(newValue: number, oldValue?: number) {
            if (oldValue !== undefined && dbValue !== oldValue) return false;
            dbValue = newValue;
            return true;
          }),
        };
        const counter = new Counter(db);

        // Act
        for (let callId = 0; callId < numCalls; ++callId) {
          s.schedule(Promise.resolve(`inc${callId + 1}`)).then(() => counter.inc());
        }
        await s.waitAll();

        // Assert
        expect(dbValue).toBe(numCalls);
      }),
    );
  })

Summary: Concurrent calls to `inc` on a shared data resource should accurately reflect the expected number of increments in the database value.


it('Checking value.isValue === true', () => {
    fc.assert(fc.property(arbResultValue(fc.integer()), (res) => {
      assert.isTrue(res.isValue());
    }));
  })

Summary: `isValue` should return true for any generated `ResultValue` instances.


it('Checking value.isError === false', () => {
    fc.assert(fc.property(arbResultValue(fc.integer()), (res) => {
      assert.isFalse(res.isError());
    }));
  })

Summary: The property ensures that `isError` returns false for values generated by `arbResultValue` with integers.


it('Checking value.getOr(v) === value.value', () => {
    fc.assert(fc.property(fc.integer(), (a) => {
      assert.equal(Result.value(a).getOr(a), a);
    }));
  })

Summary: `Result.value(a).getOr(a)` should equal `a`.


it('Checking value.getOrDie() does not throw', () => {
    fc.assert(fc.property(arbResultValue(fc.integer()), (res) => {
      res.getOrDie();
    }));
  })

Summary: `getOrDie` method on `ResultValue` should not throw an exception.


it('Checking value.or(oValue) === value', () => {
    fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => {
      assertResult(Result.value(a).or(Result.value(b)), Result.value(a));
    }));
  })

Summary: The property should hold that calling `or` on `Result.value(a)` with `Result.value(b)` results in `Result.value(a)`.


it('Checking error.or(value) === value', () => {
    fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => {
      assertResult(Result.error(a).or(Result.value(b)), Result.value(b));
    }));
  })

Summary: `Result.error(a).or(Result.value(b))` should equal `Result.value(b)`.


it('Checking value.orThunk(die) does not throw', () => {
    fc.assert(fc.property(arbResultValue(fc.integer()), (res) => {
      res.orThunk(Fun.die('dies'));
    }));
  })

Summary: Calling `value.orThunk(die)` should not throw an exception.


it('Given f :: s -> RV, checking value.bind(f).getOrDie() === f(value.getOrDie()).getOrDie()', () => {
    fc.assert(fc.property(arbResultValue(fc.integer()), fc.func(arbResultValue(fc.integer())), (res, f) => {
      assert.equal(f(res.getOrDie()).getOrDie(), res.bind(f).getOrDie());
    }));
  })

Summary: The property should hold that applying a function to a value retrieved from `ResultValue` directly yields the same result as binding the function to `ResultValue` and then retrieving the value.


it('Checking value.forall is true iff. f(value.getOrDie() === true)', () => {
    fc.assert(fc.property(arbResultValue(fc.integer()), fc.func(fc.boolean()), (res, f) => {
      assert.equal(res.forall(f), f(res.getOrDie()));
    }));
  })

Summary: `forall` returns true if and only if applying the function `f` to `getOrDie` of a result value is true.


it('Checking value.exists is true iff. f(value.getOrDie() === true)', () => {
    fc.assert(fc.property(arbResultValue(fc.integer()), fc.func(fc.boolean()), (res, f) => {
      assert.equal(res.exists(f), f(res.getOrDie()));
    }));
  })

Summary: The property ensures that `res.exists(f)` returns true if and only if `f(res.getOrDie())` is true.


it('Checking value.toOptional is always Optional.some(value.getOrDie())', () => {
    fc.assert(fc.property(arbResultValue(fc.integer()), (res) => {
      assert.equal(res.toOptional().getOrDie(), res.getOrDie());
    }));
  })

Summary: `value.toOptional` should always result in `Optional.some(value.getOrDie())`.


it('error.is === false', () => {
    fc.assert(fc.property(fc.integer(), fc.string(), (i, s) => {
      assert.isFalse(Results.is(Result.error(s), i));
    }));
  })

Summary: Verifies that `Results.is` returns false when checking if an error result matches any integer.


it('error.isValue === false', () => {
    fc.assert(fc.property(arbResultError(fc.integer()), (res) => {
      assert.isFalse(res.isValue());
    }));
  })

Summary: `isValue` should return false for `ResultError` objects generated with integer errors.


it('error.isError === true', () => {
    fc.assert(fc.property(arbResultError(fc.integer()), (res) => {
      assert.isTrue(res.isError());
    }));
  })

Summary: The property ensures that every `ResultError` generated marks `isError` as true.


test('Gen.array(gen).ofMinLength(x) *produces* arrays that shrink to length = x', () => {
    fc.assert(
      fc.property(domainGen.minimalConfig(), domainGen.gen(), genArrayLength(), (config, gen, x) => {
        const genArray = dev.Gen.array(gen).ofMinLength(x);

        const min = dev.minimalValue(genArray, config);

        expect(min).toHaveLength(x);
      }),
    );
  })

Summary: `Gen.array(gen).ofMinLength(x)` produces arrays that shrink to the minimum length `x`.


it('error.getOr(v) === v', () => {
    fc.assert(fc.property(arbResultError(fc.integer()), fc.json(), (res, json) => {
      assert.deepEqual(res.getOr(json), json);
    }));
  })

Summary: `getOr` should return the provided default value for `ResultError` instances.


it('error.getOrDie() always throws', () => {
    fc.assert(fc.property(arbResultError(fc.integer()), (res) => {
      assert.throws(() => {
        res.getOrDie();
      });
    }));
  })

Summary: `res.getOrDie()` always throws an error for `ResultError` instances.


it('error.orThunk(_ -> v) === v', () => {
    fc.assert(fc.property(fc.integer(), fc.string(), (i, s) => {
      assertResult(Result.error<number, string>(s).orThunk(() => Result.value(i)), Result.value(i));
    }));
  })

Summary: `Result.error` with `orThunk` should yield the provided fallback value wrapped in `Result.value`.


it('error.fold(_ -> x, die) === x', () => {
    fc.assert(fc.property(arbResultError(fc.integer()), fc.json(), (res, json) => {
      const actual = res.fold(Fun.constant(json), Fun.die('Should not die'));
      assert.deepEqual(actual, json);
    }));
  })

Summary: The `fold` operation on `ResultError` should return the first provided value when the first function is applied, without triggering the second function.


it('error.map returns an error', () => {
    fc.assert(fc.property(fc.integer(), (i) => {
      assertResult(Result.error(i).map(Fun.die('should not be called')), Result.error(i));
    }));
  })

Summary: `Result.error(i).map` should return an identical `Result.error(i)`.


it('Given f :: s -> RE, error.bind(f) === error', () => {
    fc.assert(fc.property(arbResultError(fc.integer()), fc.func(arbResultError(fc.integer())), (res, f) => {
      const actual = res.bind(f);
      assert.deepEqual(getErrorOrDie(actual), getErrorOrDie(res));
    }));
  })

Summary: Binding a function to a `ResultError` instance results in the same `ResultError` instance.


it('error.exists === false', () => {
    fc.assert(fc.property(fc.integer(), (i) => {
      assert.isFalse(Result.error<unknown, number>(i).exists(Fun.die('should not be called')));
    }));
  })

Summary: `Result.error` always returns an object where `exists` returns false for any integer input.


it('error.toOptional is always none', () => {
    fc.assert(fc.property(arbResultError(fc.integer()), (res) => {
      assertNone(res.toOptional());
    }));
  })

Summary: `toOptional` called on a `ResultError` always returns `none`.


it('should not generate identical IDs', () => {
    const arbId = fc.string(1, 30).map(Id.generate);
    fc.assert(fc.property(arbId, arbId, (id1, id2) => id1 !== id2));
  })

Summary: `Id.generate` should not produce identical IDs for two different runs using string inputs.


it('pure, map', () =>
    fc.assert(fc.asyncProperty(fc.integer(), fc.func(fc.string()), (i, f) => new Promise((resolve, reject) => {
      LazyValue.pure(i).map(f).get((v) => {
        eqAsync('LazyValue.map', f(i), v, reject);
        resolve();
      });
    }))))

Summary: `LazyValue.pure(i).map(f).get` should apply function `f` to integer `i`, with the result matching the expected mapped value.


it('delayed, map', () =>
    fc.assert(fc.asyncProperty(fc.integer(), fc.func(fc.string()), (i, f) => new Promise((resolve, reject) => {
      LazyValue.nu((c) => {
        setTimeout(() => {
          c(i);
        }, 2);
      }).map(f).get((v) => {
        eqAsync('LazyValue.map', f(i), v, reject);
        resolve();
      });
    }))))

Summary: `LazyValue.map` correctly applies a function to asynchronously resolved integer values.


it('parallel spec', () => fc.assert(fc.asyncProperty(fc.array(fc.integer(), 0, 20), (vals) => new Promise((resolve, reject) => {
    const lazyVals = Arr.map(vals, LazyValue.pure);
    LazyValues.par(lazyVals).get((actual) => {
      eqAsync('pars', vals, actual, reject);
      resolve();
    });
  }))))

Summary: `LazyValues.par` correctly processes an array of `LazyValue.pure` instances by returning the expected parallel results matching the input integer array.


it('map id obj = obj', () => {
    fc.assert(fc.property(fc.dictionary(fc.asciiString(), fc.integer()), (obj) => {
      const actual = Obj.map(obj, Fun.identity);
      assert.deepEqual(actual, obj);
    }));
  })

Summary: Mapping an object with the identity function should return the original object unchanged.


it('mapToArray is symmetric with tupleMap', () => {
    fc.assert(fc.property(fc.dictionary(fc.asciiString(), fc.integer()), (obj) => {
      const array = Obj.mapToArray(obj, (x, i) => ({ k: i, v: x }));

      const aKeys = Arr.map(array, (x) => x.k);
      const aValues = Arr.map(array, (x) => x.v);

      const keys = Obj.keys(obj);
      const values = Obj.values(obj);

      assert.deepEqual(Arr.sort(aKeys), Arr.sort(keys));
      assert.deepEqual(Arr.sort(aValues), Arr.sort(values));
    }));
  })

Summary: `mapToArray` and `tupleMap` maintain symmetry by ensuring the mapped array's keys and values match the original object's keys and values when sorted.


it('single key/value', () => {
    fc.assert(fc.property(
      fc.string(),
      fc.json(),
      (k: string, v: any) => {
        const o = { [k]: v };
        assert.isFalse(Obj.isEmpty(o));
      }
    ));
  })

Summary: Verifies that an object with a single key-value pair is not considered empty by `Obj.isEmpty`.


it('the value found by find always passes predicate', () => {
    fc.assert(fc.property(
      fc.dictionary(fc.asciiString(), fc.json()),
      fc.func(fc.boolean()),
      (obj, pred) => {
        // It looks like the way that fc.fun works is it cares about all of its arguments, so therefore
        // we have to only pass in one if we want it to be deterministic. Just an assumption
        const value = Obj.find(obj, (v) => {
          return pred(v);
        });
        return value.fold(() => {
          const values = Obj.values(obj);
          return !Arr.exists(values, (v) => {
            return pred(v);
          });
        }, (v) => {
          return pred(v);
        });
      }
    ));
  })

Summary: The value found by `Obj.find` from a dictionary should satisfy the given predicate, and if no value is found, no value in the dictionary should satisfy the predicate.


it('If predicate is always false, then find is always none', () => {
    fc.assert(fc.property(
      fc.dictionary(fc.asciiString(), fc.json()),
      (obj) => {
        const value = Obj.find(obj, Fun.never);
        return value.isNone();
      }
    ));
  })

Summary: `Obj.find` returns `None` when using a predicate that is always false on any dictionary of string keys and JSON values.


it('If object is empty, find is always none', () => {
    fc.assert(fc.property(
      fc.func(fc.boolean()),
      (pred) => {
        const value = Obj.find({}, pred);
        return value.isNone();
      }
    ));
  })

Summary: `Obj.find` returns none when called with an empty object, regardless of the predicate.


it('Each + set should equal the same object', () => {
    fc.assert(fc.property(
      fc.dictionary(fc.asciiString(), fc.json()),
      (obj) => {
        const values: Record<string, string> = {};
        const output = Obj.each(obj, (x, i) => {
          values[i] = x;
        });
        assert.deepEqual(values, obj);
        assert.isUndefined(output);
      }
    ));
  })

Summary: The test checks that iterating over an object with `Obj.each` and collecting its properties into a new object results in an identical object to the original, and that `Obj.each` returns `undefined`.


it('Merged with itself is itself', () => {
    fc.assert(fc.property(fc.dictionary(fc.asciiString(), fc.json()), (obj) => {
      assert.deepEqual(Merger.merge(obj, obj), obj);
    }));
  })

Summary: Merging an object with itself should result in the original object.


it('Merge(a, b) contains all the keys of b', () => {
    fc.assert(fc.property(fc.dictionary(fc.asciiString(), fc.json()), fc.dictionary(fc.asciiString(), fc.json()), (a, b) => {
      const output = Merger.merge(a, b);
      const keys = Obj.keys(b);
      const oKeys = Obj.keys(output);
      return Arr.forall(keys, (k) => {
        return Arr.contains(oKeys, k);
      });
    }));
  })

Summary: `Merger.merge` ensures the output object includes all keys from the second input object.


it('Deep-merged with identity on left', () => {
    fc.assert(fc.property(fc.dictionary(fc.asciiString(), fc.json()), (obj) => {
      assert.deepEqual(Merger.deepMerge({}, obj), obj);
    }));
  })

Summary: Deep merging an empty object with another object should return the other object unchanged.


it('Deep-merged with itself is itself', () => {
    fc.assert(fc.property(fc.dictionary(fc.asciiString(), fc.json()), (obj) => {
      assert.deepEqual(Merger.deepMerge(obj, obj), obj);
    }));
  })

Summary: Deep merging an object with itself should return the original object unchanged.


it('Deep-merge(a, Deep-merge(b, c)) === Deep-merge(Deep-merge(a, b), c)', () => {
    fc.assert(fc.property(fc.dictionary(fc.asciiString(), fc.json()), fc.dictionary(fc.asciiString(), fc.json()), fc.dictionary(fc.asciiString(), fc.json()), (a, b, c) => {
      const one = Merger.merge(a, Merger.merge(b, c));
      const other = Merger.merge(Merger.merge(a, b), c);
      assert.deepEqual(other, one);
    }));
  })

Summary: Deep merging of objects is associative, meaning `Deep-merge(a, Deep-merge(b, c))` should equal `Deep-merge(Deep-merge(a, b), c)`.


test('Gen.array(gen).ofMaxLength(x), x < 0 *produces* error; maximum must be at least 0', () => {
    fc.assert(
      fc.property(domainGen.sampleConfig(), domainGen.gen(), domainGen.integer({ max: -1 }), (config, gen, x) => {
        const genArray = dev.Gen.array(gen).ofMaxLength(x);

        expect(() => dev.sample(genArray, config)).toThrow('Maximum must be at least 0');
      }),
    );
  })

Summary: Generating an array with a maximum length less than 0 should produce an error stating that the maximum must be at least 0.


it('Checking that creating a namespace (forge) from an obj will enable that value to be retrieved by resolving (path)', () => {
    fc.assert(fc.property(
      // NOTE: This value is being modified, so it cannot be shrunk.
      fc.dictionary(fc.asciiString(),
        // We want to make sure every path in the object is an object
        // also, because that is a limitation of forge.
        fc.dictionary(fc.asciiString(),
          fc.dictionary(fc.asciiString(), fc.constant({}))
        )
      ),
      fc.array(fc.asciiString(1, 30), 1, 40),
      fc.asciiString(1, 30),
      fc.asciiString(1, 30),
      (dict, parts, field, newValue) => {
        const created = Resolve.forge(parts, dict);
        created[field] = newValue;
        const resolved = Resolve.path(parts.concat([ field ]), dict);
        assert.deepEqual(resolved, newValue);
      }
    ), { endOnFailure: true });
  })

Summary: Creating a namespace with `Resolve.forge` from an object should allow values to be correctly retrieved using `Resolve.path`.


it('nu', () => fc.assert(fc.asyncProperty(arbResult(fc.integer(), fc.integer()), (r) => new Promise((resolve, reject) => {
    FutureResult.nu((completer) => {
      completer(r);
    }).get((ii) => {
      eqAsync('eq', r, ii, reject, tResult());
      resolve();
    });
  }))))

Summary: `FutureResult.nu` processes a result using a completer and retrieves an equivalent result asynchronously.


it('fromFuture', () => fc.assert(fc.asyncProperty(fc.integer(), (i) => new Promise((resolve, reject) => {
    FutureResult.fromFuture(Future.pure(i)).get((ii) => {
      eqAsync('eq', Result.value(i), ii, reject, tResult());
      resolve();
    });
  }))))

Summary: `FutureResult.fromFuture` correctly wraps a resolved future and provides the expected result when accessed.


it('fromResult get', () => fc.assert(fc.asyncProperty(arbResult(fc.integer(), fc.integer()), (r) => new Promise((resolve, reject) => {
    FutureResult.fromResult(r).get((ii) => {
      eqAsync('eq', r, ii, reject, tResult());
      resolve();
    });
  }))))

Summary: `FutureResult.fromResult` should retrieve a result that is equivalent to the original result using asynchronous equality verification.


it('pure get', () => fc.assert(fc.asyncProperty(fc.integer(), (i) => new Promise((resolve, reject) => {
    FutureResult.pure<number, unknown>(i).get((ii) => {
      eqAsync('eq', Result.value(i), ii, reject, tResult());
      resolve();
    });
  }))))

Summary: Calls to `FutureResult.pure` with an integer should return a `Result` containing that integer upon retrieval.


it('error get', () => fc.assert(fc.asyncProperty(fc.integer(), (i) => new Promise((resolve, reject) => {
    FutureResult.error<unknown, number>(i).get((ii) => {
      eqAsync('eq', Result.error(i), ii, reject, tResult());
      resolve();
    });
  }))))

Summary: The `FutureResult.error` method returns an error containing the provided integer, and `get` correctly retrieves it, ensuring it matches `Result.error`.


it('error mapResult', () => fc.assert(fc.asyncProperty(fc.integer(), (i) => new Promise((resolve, reject) => {
    FutureResult.error(i).mapResult(Fun.die('should not be called')).get((ii) => {
      eqAsync('eq', Result.error(i), ii, reject, tResult());
      resolve();
    });
  }))))

Summary: Mapping on a `FutureResult` in an error state should not invoke the mapping function, and the result should remain an error with the same value.


it('value mapError', () => fc.assert(fc.asyncProperty(fc.integer(), (i) => new Promise((resolve, reject) => {
    FutureResult.value(i).mapError(Fun.die('should not be called')).get((ii) => {
      eqAsync('eq', Result.value(i), ii, reject, tResult());
      resolve();
    });
  }))))

Summary: `FutureResult.value(i)` processes without invoking `mapError`, ensuring error mapping is bypassed for valid values.


it('err mapError', () => {
    const f = (x: number) => x + 3;
    return fc.assert(fc.asyncProperty(fc.integer(), (i) => new Promise((resolve, reject) => {
      FutureResult.error(i).mapError(f).get((ii) => {
        eqAsync('eq', Result.error(f(i)), ii, reject, tResult());
        resolve();
      });
    })));
  })

Summary: `FutureResult.error(i).mapError(f)` transforms an error using function `f` to verify that the resulting error is correctly mapped to `Result.error(f(i))`.


it('value bindFuture value', () => fc.assert(fc.asyncProperty(fc.integer(), (i) => new Promise((resolve, reject) => {
    const f = (x: number) => x % 4;
    FutureResult.value(i).bindFuture((x) => FutureResult.value(f(x))).get((actual) => {
      eqAsync('bind result', Result.value(f(i)), actual, reject, tResult(tNumber));
      resolve();
    });
  }))))

Summary: `bindFuture` correctly applies a function to a `FutureResult` and returns a new `FutureResult` with the expected value based on the given integer.


it('bindFuture: value bindFuture error', () => fc.assert(fc.asyncProperty(fc.integer(), fc.string(), (i, s) => new Promise((resolve, reject) => {
    FutureResult.value(i).bindFuture(() => FutureResult.error(s)).get((actual) => {
      eqAsync('bind result', Result.error(s), actual, reject, tResult(tNumber));
      resolve();
    });
  }))))

Summary: `bindFuture` applied to a value should result in an error when binding to a future that produces an error.


it('error bindFuture', () => fc.assert(fc.asyncProperty(fc.integer(), (i) => new Promise((resolve, reject) => {
    FutureResult.error(i).bindFuture<never>(Fun.die('should not be called')).get((actual) => {
      eqAsync('bind result', Result.error(i), actual, reject, tResult(tNumber));
      resolve();
    });
  }))))

Summary: `bindFuture` should not invoke the provided function when called on a `FutureResult.error`.


it('returns matching keys and values', () => {
    fc.assert(fc.property(
      fc.array(fc.asciiString(1, 30)),
      (rawValues: string[]) => {
        const values = Unique.stringArray(rawValues);

        const keys = Arr.map(values, (v, i) => i);

        const output = Zip.zipToObject(keys, values);

        const oKeys = Obj.keys(output);
        assert.deepEqual(values.length, oKeys.length);

        assert.deepEqual(Arr.forall(oKeys, (oKey) => {
          const index = parseInt(oKey, 10);
          const expected = values[index];
          return output[oKey] === expected;
        }), true);
      }
    ));
  })

Summary: `Zip.zipToObject` should produce an object where keys correspond to indices and values match the specified inputs, ensuring they have matching lengths.


it('reversing a one element array is identity', () => {
    fc.assert(fc.property(fc.array(fc.integer()), (a) => {
      assert.deepEqual(Arr.reverse([ a ]), [ a ]);
    }));
  })

Summary: Reversing a single-element array should return the array unchanged.


UnitTest.test('KAssert.eqOption: success (reflexivity)', () => {
  fc.assert(fc.property(fc.integer(), (i) => {
    KAssert.eqOptional('eq', Optional.some(i), Optional.some(i));
    KAssert.eqOptional('eq', Optional.some(i), Optional.some(i), tNumber);
  }));
  KAssert.eqOptional('eq', Optional.none(), Optional.none());
})

Summary: `KAssert.eqOptional` should confirm reflexivity by verifying that two identical `Optional` objects, both containing the same integer or both being empty, are considered equal.


it('should handle two concurrent calls to "inc"', async () => {
    await fc.assert(
      fc.asyncProperty(fc.scheduler(), async (s) => {
        // Arrange
        let dbValue = 0;
        const db = {
          read: s.scheduleFunction(async function read() {
            return dbValue;
          }),
          write: s.scheduleFunction(async function write(newValue: number, oldValue?: number) {
            if (oldValue !== undefined && dbValue !== oldValue) return false;
            dbValue = newValue;
            return true;
          }),
        };
        const counter = new Counter(db);

        // Act
        s.schedule(Promise.resolve('inc1')).then(() => counter.inc());
        s.schedule(Promise.resolve('inc2')).then(() => counter.inc());
        await s.waitAll();

        // Assert
        expect(dbValue).toBe(2);
      }),
    );
  })

Summary: Concurrently calling `inc` on a `Counter` should correctly increment the database value to 2.


UnitTest.test('KAssert.eqOption: failure', () => {
  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('some(i) != some(!i) #1', () => {
      KAssert.eqOptional('eq', Optional.some(a), Optional.some(b));
    });
  }));
  fc.assert(fc.property(twoDifferentNumbers, ([ a, b ]) => {
    Assert.throws('some(i) != some(!i) #2', () => {
      KAssert.eqOptional('eq', Optional.some(a), Optional.some(b), tNumber);
    });
  }));
  fc.assert(fc.property(fc.integer(), (i) => {
    Assert.throws('none != some(i) #1', () => {
      KAssert.eqOptional('eq', Optional.none(), Optional.some(i));
    });
    Assert.throws('none != some(i) #2', () => {
      KAssert.eqOptional('eq', Optional.none(), Optional.some(i), tBoom());
    });
  }));
  fc.assert(fc.property(fc.integer(), (i) => {
    Assert.throws('some(i) != none #1', () => {
      KAssert.eqOptional('eq', Optional.some(i), Optional.none());
    });
    Assert.throws('some(i) != none #2', () => {
      KAssert.eqOptional('eq', Optional.some(i), Optional.none(), tBoom());
    });
  }));
})

Summary: `KAssert.eqOptional` should throw an error when comparing `Optional` objects that are either different values or one is `none` and the other is `some`.


Summary: `KAssert.eqOptional` throws exceptions for unequal `Optional` values, whether comparing two different `Some` values, `None` to `Some`, or `Some` to `None`.


Summary: `KAssert.eqOptional` throws an error when comparing two different `Optional` values, one being `Optional.some` with differing elements or `Optional.none` against `Optional.some`, and vice versa.


Summary: `KAssert.eqOptional` throws errors when comparing `Optional.some(a)` and `Optional.some(b)` with different values, or when comparing `Optional.some(i)` and `Optional.none()` or vice versa.


it('pure get', () => fc.assert(fc.asyncProperty(fc.integer(), (i) => new Promise((resolve, reject) =>
    Future.pure(i).get((ii) => {
      eqAsync('pure get', i, ii, reject, tNumber);
      resolve();
    })))))

Summary: Calling `Future.pure` with an integer should result in `get` returning the same integer, verified asynchronously with `eqAsync`.


it('future soon get', () => fc.assert(fc.asyncProperty(fc.integer(), (i) => new Promise((resolve, reject) =>
    Future.nu((cb) => setTimeout(() => cb(i), 3)).get((ii) => {
      eqAsync('get', i, ii, reject, tNumber);
      resolve();
    })))))

Summary: A `Future` retrieves and returns a provided integer using an asynchronous callback after a delay.


it('map', () => fc.assert(fc.asyncProperty(fc.integer(), fc.func(fc.string()), (i, f) => new Promise((resolve, reject) =>
    Future.pure(i).map(f).get((ii) => {
      eqAsync('get', f(i), ii, reject, tString);
      resolve();
    })))))

Summary: A `Future` object created with an integer applies a mapping function returning a string, and ensures the mapped result is consistent with the function's output.


it('bind', () => fc.assert(fc.asyncProperty(fc.integer(), fc.func(fc.string()), (i, f) => new Promise((resolve, reject) =>
    Future.pure(i).bind(Fun.compose(Future.pure, f)).get((ii) => {
      eqAsync('get', f(i), ii, reject, tString);
      resolve();
    })))))

Summary: The property ensures that `Future.pure` bound with a composed function, which returns `Future.pure` of a function result, retrieves a value equivalent to applying the function to the input integer.


it('anonBind', () => fc.assert(fc.asyncProperty(fc.integer(), fc.string(), (i, s) => new Promise((resolve, reject) =>
    Future.pure(i).anonBind(Future.pure(s)).get((ii) => {
      eqAsync('get', s, ii, reject, tString);
      resolve();
    })))))

Summary: The property should hold that binding an integer future to a string future using `anonBind` results in the second future's value being returned.


it('parallel spec', () => fc.assert(fc.asyncProperty(fc.array(fc.tuple(fc.integer(1, 10), fc.integer())), (tuples) => new Promise((resolve, reject) =>
    Futures.par(Arr.map(tuples, ([ timeout, value ]) => Future.nu((cb) => setTimeout(() => cb(value), timeout)))).get((ii) => {
      eqAsync('pars', tuples.map(([ _, i ]) => i), ii, reject, tArray(tNumber));
      resolve();
    }))))
  )

Summary: `Futures.par` processes an array of asynchronous operations and confirms they resolve to the expected values in parallel, based on an array of integer tuples representing timeouts and values.


it('mapM spec', () =>
    fc.assert(fc.asyncProperty(fc.array(fc.tuple(fc.integer(1, 10), fc.integer())), (tuples) => new Promise((resolve, reject) =>
      Futures.mapM(tuples, ([ timeout, value ]) => Future.nu((cb) => setTimeout(() => cb(value), timeout))).get((ii) => {
        eqAsync('pars', tuples.map(([ _, i ]) => i), ii, reject, tArray(tNumber));
        resolve();
      }))))
  )

Summary: `Futures.mapM` processes an array of tuples asynchronously, verifying that the output matches the sequence of values extracted from the input tuples.


it('TINY-6891: Should be able to convert to and from numbers/list numbering', () => {
    const arbitrary = Arr.map([
      fc.mapToConstant({ num: 26, build: (v) => String.fromCharCode(65 + v) }),
      fc.mapToConstant({ num: 26, build: (v) => String.fromCharCode(97 + v) }),
      fc.mapToConstant({ num: 10, build: (v) => v.toString() })
    ], (c) => fc.stringOf(c, 1, 5));

    fc.assert(fc.property(
      fc.oneof(...arbitrary),
      (start) => {
        assert.equal(
          start,
          parseStartValue(start).map(parseDetail).getOrDie(),
          'Should be initial start value'
        );
      }
    ), { endOnFailure: true });
  })

Summary: The test verifies that converting a string representation of letters or numbers to a parsed value and back results in the original string.


it('no initial data', () => {
      const dialogChange = DialogChanges.init({ title: '', text: '' } as LinkDialogData, { } as LinkDialogCatalog);

      fc.assert(fc.property(fc.webUrl(), fc.asciiString(), fc.asciiString(), (url, title, text) => {
        const data = Fun.constant({ url: {
          value: url,
          meta: { title, text }
        }} as LinkDialogData);
        const dataNoMeta = Fun.constant({ url: {
          value: url,
          meta: { }
        }} as LinkDialogData);

        Assert.eq('on url change should include url title and text',
          Optional.some<Partial<LinkDialogData>>({ title, text }),
          dialogChange.onChange(data, { name: 'url' }),
          tOptional()
        );

        Assert.eq('on url change should fallback to url for text',
          Optional.some<Partial<LinkDialogData>>({ title: '', text: url }),
          dialogChange.onChange(dataNoMeta, { name: 'url' }),
          tOptional()
        );
      }));
    })

Summary: Verifies that when `DialogChanges` is initialized with no initial data, changing the URL with meta data includes the title and text, and changing the URL without meta data defaults the text to the URL itself.


it('with original data', () => {
      const dialogChange = DialogChanges.init({ title: 'orig title', text: 'orig text' } as LinkDialogData, { } as LinkDialogCatalog);
      const dialogChangeNoTitle = DialogChanges.init({ title: '', text: 'orig text' } as LinkDialogData, { } as LinkDialogCatalog);
      const dialogChangeNoText = DialogChanges.init({ title: 'orig title', text: '' } as LinkDialogData, { } as LinkDialogCatalog);

      fc.assert(fc.property(fc.webUrl(), fc.asciiString(), fc.asciiString(), (url, title, text) => {
        const data = Fun.constant({ url: {
          value: url,
          meta: { title, text }
        }} as LinkDialogData);

        Assert.eq('on url change should not try to change title and text',
          Optional.none(),
          dialogChange.onChange(data, { name: 'url' }),
          tOptional()
        );

        Assert.eq('No Title - on url change should only try to change title',
          Optional.some<Partial<LinkDialogData>>({ title }),
          dialogChangeNoTitle.onChange(data, { name: 'url' }),
          tOptional()
        );

        Assert.eq('No Text - on url change should only try to change text',
          Optional.some<Partial<LinkDialogData>>({ text }),
          dialogChangeNoText.onChange(data, { name: 'url' }),
          tOptional()
        );
      }));
    })

Summary: DialogChanges should not alter both title and text on a URL change if both are originally present, should only alter the title if absent, and should only alter the text if absent.


it('TINY-4773: multiple @ characters', () => {
    const editor = hook.editor();
    fc.assert(fc.property(fc.hexaString(0, 30), fc.hexaString(0, 30), fc.hexaString(0, 30), (s1, s2, s3) => {
      assertNoLink(editor, `${s1}@@${s2}@.@${s3}`, `${s1}@@${s2}@.@${s3}`);
    }));
  })

Summary: Ensures no links are created in the editor for strings composed of multiple '@' characters.


it('TINY-9226: basic property - no outside constraints', () => {
        fc.assert(
          fc.property(arbBounds, arbBounds, (original, constraint) => {
            const actual = Boxes.constrain(original, constraint);
            assert.isAtLeast(actual.x, constraint.x);
            assert.isAtMost(actual.right, constraint.right);
            assert.isAtLeast(actual.y, constraint.y);
            assert.isAtMost(actual.bottom, constraint.bottom);
          })
        );
      })

Summary: `Boxes.constrain` adjusts a box's boundaries to fit within specified constraints by ensuring the box's coordinates are at least and at most the constraint values for each side.


it('should be able to call multiple /drop-deactivated at the same time', async () => {
    await fc.assert(
      fc.asyncProperty(
        fc.uniqueArray(
          fc.record({
            id: fc.uuid({ version: 4 }),
            name: fc.string(),
            deactivated: fc.boolean(),
          }),
          { selector: (u) => u.id },
        ),
        fc.integer({ min: 1, max: 5 }),
        fc.scheduler({
          // In the case of supertest, as a user you MUST define a custom `act` function
          // if you want to run multiple queries at the same time. The following one adds
          // some extra timers so that supertest can push promises in the queue in time.
          // Second test is the very same test but outside of supertest.
          act: async (f) => {
            await new Promise((r) => setTimeout(r, 0));
            await f();
          },
        }),
        async (allUsers, num, s) => {
          // Arrange
          let knownUsers = allUsers;
          const getAllUsers = DbMock.getAllUsers as MockedFunction<typeof DbMock.getAllUsers>;
          const removeUsers = DbMock.removeUsers as MockedFunction<typeof DbMock.removeUsers>;
          getAllUsers.mockImplementation(
            s.scheduleFunction(async function getAllUsers() {
              return knownUsers;
            }),
          );
          removeUsers.mockImplementation(
            s.scheduleFunction(async function removeUsers(ids) {
              const sizeBefore = knownUsers.length;
              knownUsers = knownUsers.filter((u) => !ids.includes(u.id));
              return sizeBefore - knownUsers.length;
            }),
          );

          // Act
          const r = request(app);
          const queries = [];
          for (let index = 0; index !== num; ++index) {
            queries.push(r.get('/drop-deactivated?id=' + index).send());
          }
          const out = await s.waitFor(Promise.all(queries));

          // Assert
          for (const outQuery of out) {
            expect(outQuery.body.status).toBe('success');
          }
        },
      ),
    );
  })

Summary: Multiple `/drop-deactivated` API calls should succeed simultaneously when invoked with unique user records.


it('TINY-9226: basic property', () => {
        fc.assert(
          fc.property(arbBounds, arbBounds, fc.array(arbBounds), (original, first, rest) => {
            const constraints = [ first ].concat(rest);
            const all = [ original ].concat(constraints);
            const actual = Boxes.constrainByMany(original, constraints);
            const optLargestLeft = Arr.last(sortNumbers(Arr.map(all, (c) => c.x)));
            const optLargestTop = Arr.last(sortNumbers(Arr.map(all, (c) => c.y)));
            const optSmallestRight = Arr.head(sortNumbers(Arr.map(all, (c) => c.right)));
            const optSmallestBottom = Arr.head(sortNumbers(Arr.map(all, (c) => c.bottom)));

            const assertOpt = (label: string, optValue: Optional<number>, actualValue: number): void => {
              optValue.fold(
                () => assert.fail('There were no candidates. Actual value: ' + actualValue),
                (v) => assert.equal(
                  actualValue,
                  v,
                  `Property ${label}. Expected: ${v}, Actual: ${actualValue}, \n
                   All: ${JSON.stringify(all, null, 2)}`
                )
              );
            };

            assertOpt('left', optLargestLeft, actual.x);
            assertOpt('right', optSmallestRight, actual.right);
            assertOpt('top', optLargestTop, actual.y);
            assertOpt('bottom', optSmallestBottom, actual.bottom);
          })
        );
      })

Summary: `Boxes.constrainByMany` adjusts the `original` box's edges to match expected constraints from the largest left, largest top, smallest right, and smallest bottom derived from a collection of bounding boxes.


test(
    'Typical usage - enqueue 0-1000 tasks & process them (with manual polling)',
    { timeout: seconds(30) },
    async () => {
      await fc.assert(
        fc.asyncProperty(
          fc.scheduler(),
          fc.array(
            fc.record({
              taskId: fc.uuid({ version: 4 }),
              payload: fc.jsonValue(),
            }),
            { minLength: 0, maxLength: 1000 },
          ),
          fc.constantFrom(...executorStrategies()),
          fc.integer({min: 1, max: 10 }),
          async (scheduler, tasksToRun, executorStrategy, concurrency) => {
            // TODO: Move this check + error handling to workhorse.queue() and verify payload can be stringified and read back to itself
            tasksToRun = tasksToRun.filter(isValidTask);
            const taskResults: TaskResult[] = [];

            const runTask: RunTask = async (taskId, payload) => {
              taskResults.push({ taskId, payload });
              return Promise.resolve(undefined);
            };

            const workhorse = await createWorkhorse(runTask, {
              taskExecution: executorStrategy,
              concurrency,
            });

            tasksToRun.forEach((task) => {
              // eslint-disable-next-line @typescript-eslint/no-floating-promises
              scheduler.schedule(workhorse.queue(task.taskId, task.payload));
            });

            expect(scheduler.count()).toBe(tasksToRun.length);

            await scheduler.waitAll();

            expect(scheduler.count()).toBe(0);

            const taskMonitor = { remaining: tasksToRun.length };
            workhorse.subscribe(Subscriptions.TaskMonitor.Updated, (monitor) => {
              taskMonitor.remaining = monitor.remaining;
            });

            while (taskMonitor.remaining !== 0) {
              await workhorse.poll();
            }
            const status = await workhorse.getStatus();
            expect(status).toEqual({ queued: 0, failed: 0, executing: 0, successful: tasksToRun.length});
            // We do this because since we transforms the payload of each task to JSON there's
            // a small chance that when parsed it will differ from the original
            // (eg JSON.parse(JSON.stringify({"": -0})) !== JSON.parse(JSON.stringify({"": 0})))
            expect(JSON.stringify(taskResults)).toEqual(JSON.stringify(tasksToRun));
          }
        ),
        { verbose: 2, numRuns: 500 }
      );
    }
  )

Summary: Enqueuing and processing 0-1000 tasks with manual polling should result in all tasks being successfully executed with correct task status and payload integrity across different execution strategies and concurrency levels.


test('Tasks are processed atomically in the order they were added (high concurrency)', async () => {
    await fc.assert(
      fc.asyncProperty(
        fc.scheduler(),

        fc.uniqueArray(fc.nat(), { minLength: 1, maxLength: 36 }),
        fc.integer({ min: 20, max: 100 }),
        async (scheduler, taskIds, concurrency) => {
          const executedTasks: string[] = [];
          const runTaskPromises: Promise<TaskResult>[] = [];
          const expectedIds = [...taskIds].map((id) => `${id}`);

          // Wrap `runTask` with scheduler and promise tracking
          const runTask = async (taskId: string, _payload: Payload): Promise<TaskResult> => {
            const taskPromise = scheduler.schedule(
              new Promise<TaskResult>((resolve) => {
                executedTasks.push(taskId);
                resolve(undefined);
              })
            );
            runTaskPromises.push(taskPromise); // Track each task's promise
            return await taskPromise;
          };

          const workhorse = await createWorkhorseFixture(runTask, { concurrency });

          // Queue tasks
          const queuePromises = taskIds.map((id) =>
            scheduler.schedule(workhorse.queue(`${id}`, {}))
          );
          await scheduler.waitFor(Promise.all(queuePromises));

          // Poll tasks
          const pollPromises = Array.from({ length: taskIds.length }, () =>
            scheduler.schedule(workhorse.poll())
          );
          await scheduler.waitFor(Promise.all(pollPromises));

          // Wait for all `runTask` promises
          await scheduler.waitFor(Promise.all(runTaskPromises));

          //console.log('expected: ', [...expectedIds]);
          //console.log('actual:   ', [...executedTasks]);
          // Validate the results
          expect(expectedIds).toEqual(executedTasks);
        }
      ),
      { verbose: 2, numRuns: 100 }
    );
  })

Summary: Tasks should be executed atomically in the exact order they were added, even under high concurrency.


test('Tasks are processed atomically in the order they were added (low concurrency)', async () => {
    await fc.assert(
      fc.asyncProperty(
        fc.scheduler(),

        fc.uniqueArray(fc.nat(), { minLength: 1, maxLength: 100 }),
        fc.integer({ min: 1, max: 10 }),
        async (scheduler, taskIds, concurrency) => {
          const expectedIds = [...taskIds].map((id) => `${id}`);
          const actualIds: string[] = [];

          // Wrap `runTask` with scheduler and promise tracking
          const runTask = async (taskId: string, _payload: Payload): Promise<TaskResult> => {
            actualIds.push(taskId);
            return Promise.resolve(undefined);
          };

          // Create the workhorse instance
          const workhorse = await createWorkhorseFixture(runTask, {
            concurrency,
            plugins: [new TaskMonitor()],
          });

          const status = { remaining: taskIds.length };
          workhorse.subscribe(Subscriptions.TaskMonitor.Updated, ({ remaining }) => {
            status.remaining = remaining;
          });

          const addTasksSequence = expectedIds.map((taskId) => () => workhorse.queue(taskId, {}));
          scheduler.scheduleSequence(addTasksSequence);

          await scheduler.waitAll();

          while (status.remaining > 0) {
            await workhorse.poll();
          }

          const expectedStatus = { queued: 0, executing: 0, successful: taskIds.length, failed: 0 };
          const finalStatus = await workhorse.getStatus();

          expect(expectedStatus).toEqual(finalStatus);
          expect(expectedIds).toEqual(actualIds);
        }
      ),
      { verbose: 2, numRuns: 100 }
    );
  })

Summary: Tasks should be processed atomically and in the order they were added, even under low concurrency conditions.


it('Fuzzing - tasks are processed atomically with retries until all succeed', async () => {
    // Helper to create a deterministic task runner using an infinite stream of probabilities
    const createTaskFunction = (taskProbStream: IterableIterator<number>) => {
      const executedTaskSet = new Set<string>();
      return async (taskId: string, _payload: Payload): Promise<TaskResult> => {
        // Use the next value from the probability stream
        const taskFailureProb = taskProbStream.next().value * 1.0;
        const currentFailureProb = taskProbStream.next().value * 2.0; // make the task have a slight bias towards success
        const shouldFail = taskFailureProb > currentFailureProb; // Fail if probability is lower
        if (shouldFail) {
          //console.log(`${taskId}`, 'failure: ', taskFailureProb, currentFailureProb);
          throw new Error(`Task ${taskId} failed`);
        } else {
          if (executedTaskSet.has(taskId)) {
            //console.log(`Task ${taskId} has already been executed`);
            throw new Error(`Task ${taskId} has already been executed`);
          }

          //console.log(`${taskId}`, 'succcess: ', taskFailureProb, currentFailureProb);
        }
        executedTaskSet.add(taskId);
        return Promise.resolve(undefined);
      };
    };

    await fc.assert(
      fc.asyncProperty(
        fc.uniqueArray(fc.uuid(), { minLength: 1, maxLength: 36 }), // Unique task IDs
        fc.noShrink(fc.infiniteStream(fc.integer({ min: 0, max: 100 }))), // Infinite stream of probabilities
        fc.integer({ min: 30, max: 30 }), // Concurrency level
        async (taskIds, probabilityStream, concurrency) => {
          const totalTasks = taskIds.map((id) => id);
          const runTask = createTaskFunction(probabilityStream);

          const workhorse = await createWorkhorseFixture(runTask, {
            concurrency,
            taskExecution: TaskExecutorStrategy.DETACHED,
          });

          // Queue tasks
          const queuePromises = taskIds.map((id) => workhorse.queue(id, {}));
          await Promise.all(queuePromises);

          // Poll until all tasks succeed
          let done = false;
          while (!done) {
            await workhorse.poll();
            //console.log('Done polling');
            // Check the task queue status
            //console.log('Check status');
            const status = await workhorse.getStatus();
            //console.log('Status ', status);
            if (status.successful === totalTasks.length) {
              done = true;
            }
            //console.log('Done check status');
            if (status.failed > 0) {
              //console.log('*** requeuing')
              await workhorse.requeue();
              //const status = await workhorse.getStatus();
              //console.log('Status ', status);
            }
          }

          // Ensure all tasks were executed successfully
          expect(totalTasks.length).toBe((await workhorse.getStatus()).successful);
        }
      ),
      { verbose: 2, numRuns: 100 }
    );
  })

Summary: Tasks should be processed atomically with retries until all succeed, ensuring progress despite failures.


test.concurrent('Fuzzing - start/stop', { timeout: seconds(30) }, async () => {
    await fc.assert(
      fc.asyncProperty(
        fc.uniqueArray(fc.uuid(), { minLength: 1, maxLength: 10 }),
        fc.infiniteStream(fc.boolean()),
        fc.integer({ min: 1, max: 10 }),
        async (taskIds: string[], coinToss: Stream<boolean>, concurrency: number) => {
          const executedTasks: string[] = [];
          const expectedIds = [...taskIds].map((id) => id);

          const runTask = (taskId: string, _payload: Payload): Promise<TaskResult> => {
            executedTasks.push(taskId);
            return new Promise((resolve) => {
              resolve(undefined);
            });
          };

          const options = defaultOptions();
          options.concurrency = concurrency;
          options.taskExecution = TaskExecutorStrategy.PARALLEL;
          options.poll.auto = true;
          options.poll.interval = millisec(1);
          const workhorse = await createWorkhorseFixture(runTask, options);

          // Queue tasks
          for (const taskId of taskIds) {
            await workhorse.queue(taskId, {});
          }

          // Randomly start/stop poller
          for (const result of coinToss) {
            if (result) {
              workhorse.startPoller();
            } else {
              workhorse.stopPoller();
            }

            const status = await workhorse.getStatus();
            if (status.queued === 0 && status.executing === 0) {
              break;
            }
            //console.log(status);
          }
          // TODO: Should workhorse.shutdown() be removed as part of the interface?
          // TODO: Only reason to keep it would be: freeing resources & removing db entirely?
          const finalStatus = await workhorse.getStatus();

          expect(finalStatus).toEqual({
            queued: 0,
            executing: 0,
            successful: taskIds.length,
            failed: 0,
          });

          // Ensure all tasks executed successfully
          expect(executedTasks).toEqual(expectedIds);
        }
      ),
      { verbose: 2, numRuns: 100 }
    );
  })

Summary: The property ensures that when tasks are queued and a poller randomly starts and stops, all tasks are executed successfully, and the final status reflects zero queued, executing, and failed tasks, with all tasks marked as successful.


test.concurrent('workhorse.run', { timeout: seconds(30) }, async () => {
    await fc.assert(
      fc.asyncProperty(
        fc.scheduler(), // param 1 = scheduler
        fc.integer({ min: 1, max: 10 }), // param 2 = concurrency
        fc.integer({ min: 1, max: 50 }), // param 3 = poll interval
        async (scheduler: Scheduler, concurrency: number, sleep) => {
          //console.time('startup');
          const runTask = async (_taskId: string, payload: Payload): Promise<TaskResult> => {
            return Promise.resolve(payload);
          };
          const config = defaultOptions();
          config.concurrency = concurrency;
          config.poll.interval = millisec(sleep);
          const workhorse = await createWorkhorseFixture(runTask);
          workhorse.startPoller();

          const expectedResults = [
            { taskId: 'task-1' },
            { taskId: 'task-2' },
            { taskId: 'task-3' },
          ];
          const taskIds = ['task-1', 'task-2', 'task-3'];
          const promises = [];

          // Note: The current workhorse.run() implementation is quite slow,
          // and you're almost always better of using workhorse.queue()
          // workhorse.run() is only useful when you need to await the return value of the task
          for (const taskId of taskIds) {
            promises.push(scheduler.schedule(workhorse.run(taskId, { taskId })));
          }
          //console.timeEnd('startup');
          //console.time('waiting')
          const actualResults = await scheduler.waitFor(Promise.all(promises));
          //console.timeEnd('waiting');
          expect(actualResults).toEqual(expectedResults);
        }
      ),
      { verbose: 2, numRuns: 20 }
    );
  })

Summary: `workhorse.run` should return expected results for tasks when executed with varying concurrency and polling intervals using a scheduler.


it('Timestamp to DateTime', async () => {
    const dateTimeContract = await loadFixture(fixture)

    await fc.assert(
      fc.asyncProperty(
        fc.integer().filter((x) => x >= 0),
        async (timestamp) => {
          const dateTime = await dateTimeContract.timestampToDateTime(timestamp)
          const date = new Date(timestamp * 1_000)

          expect(dateTime.year.toNumber()).equal(date.getUTCFullYear())
          expect(dateTime.month.toNumber()).equal(date.getUTCMonth() + 1)
          expect(dateTime.day.toNumber()).equal(date.getUTCDate())
          expect(dateTime.hour.toNumber()).equal(date.getUTCHours())
          expect(dateTime.minute.toNumber()).equal(date.getUTCMinutes())
          expect(dateTime.second.toNumber()).equal(date.getUTCSeconds())
        }
      )
    )
  })

Summary: Converting a positive integer timestamp to a DateTime object should match the equivalent UTC date and time components.


Summary: The `timestampToDateTime` function should correctly convert a non-negative integer timestamp to its equivalent UTC `DateTime` components (year, month, day, hour, minute, second).


it("should convert Text to a string", () => {
      expect.assertions(100);

      fc.assert(fc.property(text, toStringDefinition));
    })

Summary: Converting `Text` to a string maintains the expected properties defined in `toStringDefinition`.


it("should preserve identity morphisms", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(task(fc.anything(), fc.anything()), mapIdentity),
      );
    })

Summary: The test checks that identity morphisms are preserved for tasks generated with arbitrary inputs.


it("should preserve identity morphisms", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(task(fc.anything(), fc.anything()), mapOkayIdentity),
      );
    })

Summary: The test verifies that identity morphisms are preserved within asynchronous tasks.


it("should preserve identity morphisms", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(task(fc.anything(), fc.anything()), mapFailIdentity),
      );
    })

Summary: Identity morphisms should be preserved in the context of tasks with any input.


it("should agree with map", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), fc.anything()),
          fc.anything(),
          fc.anything(),
          replaceDefinition,
        ),
      );
    })

Summary: The property being tested checks that the `task` function behaves consistently with `map`, using varied inputs and the `replaceDefinition` function.


it("should agree with mapOkay", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), fc.anything()),
          fc.anything(),
          replaceOkayDefinition,
        ),
      );
    })

Summary: The properties of tasks should be consistent with `replaceOkayDefinition` when using `mapOkay` with any generated values.


it("should agree with mapFail", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), fc.anything()),
          fc.anything(),
          replaceFailDefinition,
        ),
      );
    })

Summary: The test checks that a function behaves consistently with the `mapFail` function using various input tasks and parameters.


it("should have a left identity", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(task(fc.anything(), fc.anything()), andLeftIdentity),
      );
    })

Summary: The test checks that the `andLeftIdentity` property holds for tasks created with arbitrary inputs.


it("should have a right identity", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(task(fc.anything(), fc.anything()), andRightIdentity),
      );
    })

Summary: The property ensures that applying the right identity function to a task does not alter the task's result.


it("should be associative", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), fc.anything()),
          task(fc.anything(), fc.anything()),
          task(fc.anything(), fc.anything()),
          andAssociativity,
        ),
      );
    })

Summary: The property validates that the `andAssociativity` function maintains associativity across multiple `task` combinations with arbitrary results.


it("should have a left annihilator", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), fc.anything()),
          andLeftAnnihilation,
        ),
      );
    })

Summary: The test checks that the `andLeftAnnihilation` property holds for tasks generated with any values, ensuring they exhibit a left annihilator behavior.


it("should agree with and", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), fc.anything()),
          task(fc.anything(), fc.anything()),
          andThenDefinition,
        ),
      );
    })

Summary: The agreement between two tasks and the `andThenDefinition` should hold consistently.


it("should agree with and", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), fc.anything()),
          task(fc.anything(), fc.anything()),
          andWhenDefinition,
        ),
      );
    })

Summary: The test ensures that the combination of two tasks with `andWhenDefinition` behaves consistently with expected results.


it("should have a left identity", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(task(fc.anything(), fc.anything()), orLeftIdentity),
      );
    })

Summary: The test ensures that a task constructed with any value satisfies the left identity property with `orLeftIdentity`.


it("should have a right identity", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(task(fc.anything(), fc.anything()), orRightIdentity),
      );
    })

Summary: The property checks that a task satisfies the right identity law using the `orRightIdentity` function.


it("should be associative", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), fc.anything()),
          task(fc.anything(), fc.anything()),
          task(fc.anything(), fc.anything()),
          orAssociativity,
        ),
      );
    })

Summary: The property checks that the `orAssociativity` function maintains associativity for tasks created with any values.


it("should have a left annihilator", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), fc.anything()),
          orLeftAnnihilation,
        ),
      );
    })

Summary: The test checks that an unspecified operation or behavior exhibits a left annihilator property across various tasks.


it("should agree with or", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), fc.anything()),
          task(fc.anything(), fc.anything()),
          orElseDefinition,
        ),
      );
    })

Summary: The test checks that the behavior of combining tasks with the `orElseDefinition` function is consistent with the logical "or" operation.


it("should agree with or", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), fc.anything()),
          task(fc.anything(), fc.anything()),
          orErstDefinition,
        ),
      );
    })

Summary: The test checks if `orErstDefinition` aligns with the behavior of two tasks processed by `task`.


it("should have a left okay identity", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          fc.anything(),
          fc.func(task(fc.anything(), fc.anything())),
          flatMapLeftIdentityOkay,
        ),
      );
    })

Summary: Verifies the left identity property using a task function and an async computation.


it("should have a left fail identity", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          fc.anything(),
          fc.func(task(fc.anything(), fc.anything())),
          flatMapLeftIdentityFail,
        ),
      );
    })

Summary: Verifies that the property of having a left fail identity holds for operations involving tasks and functions over arbitrary inputs.


it("should have a right okay identity and a right fail identity", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), fc.anything()),
          flatMapRightIdentity,
        ),
      );
    })

Summary: The function verifies the right identity property for tasks by checking both successful and failing conditions using `flatMapRightIdentity`.


it("should be associative", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), fc.anything()),
          fc.func(task(fc.anything(), fc.anything())),
          fc.func(task(fc.anything(), fc.anything())),
          fc.func(task(fc.anything(), fc.anything())),
          fc.func(task(fc.anything(), fc.anything())),
          flatMapAssociativity,
        ),
      );
    })

Summary: Associativity is tested by verifying that the order of applying transformations, defined by a series of functions on tasks, does not affect the final result.


it("should agree with flatMap", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), fc.anything()),
          fc.func(task(fc.anything(), fc.anything())),
          flatMapOkayDefinition,
        ),
      );
    })

Summary: The result from applying `flatMap` on tasks should be consistent with a defined specification.


it("should agree with flatMap", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), fc.anything()),
          fc.func(task(fc.anything(), fc.anything())),
          flatMapFailDefnition,
        ),
      );
    })

Summary: The test verifies that a task function composed with `flatMap` behaves consistently with the `flatMapFailDefinition`.


it("should agree with flatMap", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(
            task(fc.anything(), fc.anything()),
            task(fc.anything(), fc.anything()),
          ),
          flattenDefinition,
        ),
      );
    })

Summary: The property being tested is whether a task operation agrees with the behavior of `flatMap`, following the provided `flattenDefinition`.


it("should agree with flatMapOkay", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(task(fc.anything(), fc.anything()), fc.anything()),
          flattenOkayDefinition,
        ),
      );
    })

Summary: The property should hold when using a task with `flattenOkayDefinition`, ensuring it behaves consistently with `flatMapOkay` across diverse inputs.


it("should agree with flatMapFail", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), task(fc.anything(), fc.anything())),
          flattenFailDefinition,
        ),
      );
    })

Summary: The test checks that the behavior of a task operation is consistent with `flatMapFail` across randomized task inputs.


it("should be equivalent to multiple flatMap calls", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.integer({ min: 1 }), fc.integer({ min: 1 })),
          fc.constant((n: number) => Task.okay(collatz(n))),
          fc.constant((n: number) => Task.fail(collatz(n))),
          flatMapUntilEquivalence,
        ),
      );
    })

Summary: Multiple `flatMap` calls should produce equivalent results in the context of tasks with `Task.okay` and `Task.fail` transformations, ensuring consistency across transformations applied until a certain equivalence is reached.


it("should fail to cast non-number arrays", () => {
      expect.assertions(100);
      fc.assert(
        fc.property(
          fc.array(
            fc.anything().filter((input) => typeof input !== "number"),
            { minLength: 1 }
          ),
          (input) => {
            expect(castNums(input)).toStrictEqual({
              status: "failure",
              expected: "array",
              items: input.map((actual) => ({
                status: "failure",
                expected: "number",
                actual
              })),
              actual: input
            });
          }
        )
      );
    })

Summary: Casting non-number arrays should result in a failure status with details about each non-number item.


it("should be equivalent to multiple flatMapOkay calls", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.integer({ min: 1 }), fc.anything()),
          fc.constant((n: number) => Task.okay(collatz(n))),
          flatMapOkayUntilEquivalence,
        ),
      );
    })

Summary: The property ensures that a task sequence processed with `flatMapOkayUntilEquivalence` is equivalent to multiple calls to `flatMapOkay`.


it("should be equivalent to multiple flatMapFail calls", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), fc.integer({ min: 1 })),
          fc.constant((n: number) => Task.fail(collatz(n))),
          flatMapFailUntilEquivalence,
        ),
      );
    })

Summary: `flatMapFailUntilEquivalence` should consistently produce results equivalent to multiple calls of `flatMapFail`.


it("should be its own inverse", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(task(fc.anything(), fc.anything()), commuteInverse),
      );
    })

Summary: A task applied twice with a function should return the original value (commutative inverse property).


it("should agree with effect", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), fc.anything()),
          fc.func(fc.anything()),
          effectMapDefinition,
        ),
      );
    })

Summary: The test checks that the behavior of a `task` function with arbitrary inputs and a random function aligns with the `effectMapDefinition`.


it("should be equivalent to multiple flatMap calls", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.integer({ min: 1 }), fc.anything()),
          fc.constant(isPowerOfTwo),
          fc.constant((n: number) => Task.okay(hotpo(n))),
          fc.func(task(fc.anything(), fc.anything())),
          fromGeneratorEquivalence,
        ),
      );
    })

Summary: The test ensures that a series of `flatMap` calls applied to tasks is equivalent under different functional transformations and conditions.


it("should throw the value when the generator yields Task.fail", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          task(fc.anything(), fc.anything()),
          task(fc.anything(), fc.anything()),
          fromGeneratorThrow,
        ),
      );
    })

Summary: The test checks that when a generator yields `Task.fail`, the value is thrown.


it("should return Fail when the generator throws an Exception", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          result(fc.anything(), fc.anything()),
          fc.anything(),
          fromGeneratorCatch,
        ),
      );
    })

Summary: The property should result in "Fail" when `fromGeneratorCatch` executes a generator that throws an exception.


it("should return Okay when the generator returns", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          result(fc.anything(), fc.anything()),
          fc.anything(),
          fromGeneratorReturn,
        ),
      );
    })

Summary: The function `fromGeneratorReturn` should return `Okay` when the associated generator completes, across a variety of input values.


it("should be associative", () => {
        expect.assertions(100);

        fc.assert(fc.property(value, value, value, appendAssociativity));
      })

Summary: The property verifies that the `appendAssociativity` function maintains associativity for the `value` type.


it("should convert Fail to a string", () => {
      expect.assertions(100);

      fc.assert(fc.property(fc.anything(), toStringFail));
    })

Summary: `toStringFail` should correctly convert any input into a string representation of `Fail`.


it("should fold the Result", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.anything(), fc.anything()),
          fc.func(fc.anything()),
          fc.func(fc.anything()),
          foldEquivalence,
        ),
      );
    })

Summary: The property validates that folding a `Result` using two arbitrary functions maintains equivalence as defined by `foldEquivalence`.


it("should preserve identity morphisms", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(result(fc.anything(), fc.anything()), mapOkayIdentity),
      );
    })

Summary: `mapOkayIdentity` ensures identity morphisms are preserved when applied to result structures.


it("should preserve identity morphisms", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(result(fc.anything(), fc.anything()), mapFailIdentity),
      );
    })

Summary: Identity morphisms in `result` should remain unchanged when `mapFailIdentity` is applied.


it("should agree with map", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.anything(), fc.anything()),
          fc.anything(),
          fc.anything(),
          replaceDefinition,
        ),
      );
    })

Summary: The test checks if a certain property relating to a custom `result` type operation is consistent with the behavior of a map operation.


it("should agree with mapOkay", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.anything(), fc.anything()),
          fc.anything(),
          replaceOkayDefinition,
        ),
      );
    })

Summary: The test checks that the `result` function behaves consistently with `mapOkay` when given arbitrary inputs and the `replaceOkayDefinition`.


it("should agree with mapFail", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.anything(), fc.anything()),
          fc.anything(),
          replaceFailDefinition,
        ),
      );
    })

Summary: The property should hold that the result agrees with `mapFail` when given any value and a `replaceFailDefinition`.


it("should have a left identity", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(result(fc.anything(), fc.anything()), andLeftIdentity),
      );
    })

Summary: `andLeftIdentity` maintains the left identity property for `result` function across various inputs.


it("should have a right identity", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(result(fc.anything(), fc.anything()), andRightIdentity),
      );
    })

Summary: The property checks that applying the `andRightIdentity` function to any generated `result` maintains a right identity.


it("should be associative", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.anything(), fc.anything()),
          result(fc.anything(), fc.anything()),
          result(fc.anything(), fc.anything()),
          andAssociativity,
        ),
      );
    })

Summary: `andAssociativity` should hold true for any three `result` instances created from arbitrary values.


it("should have a left annihilator", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(result(fc.anything(), fc.anything()), andLeftAnnihilation),
      );
    })

Summary: `andLeftAnnihilation` confirms that applying the operation with a left annihilator on any input results in the annihilator itself.


it("should agree with and", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.anything(), fc.anything()),
          result(fc.anything(), fc.anything()),
          andThenDefinition,
        ),
      );
    })

Summary: The test verifies that the behavior of combining two `result` values using `andThenDefinition` is consistent with a logical `and` operation.


it("should agree with and", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.anything(), fc.anything()),
          result(fc.anything(), fc.anything()),
          andWhenDefinition,
        ),
      );
    })

Summary: The test ensures that two result instances, combined with a function or condition (`andWhenDefinition`), are in agreement with logical conjunction behavior.


it("should have a left identity", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(result(fc.anything(), fc.anything()), orLeftIdentity),
      );
    })

Summary: The `orLeftIdentity` function should satisfy the left identity property for any generated result.


it("should have a right identity", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(result(fc.anything(), fc.anything()), orRightIdentity),
      );
    })

Summary: `orRightIdentity` function should maintain the right identity property for any `result` containing arbitrary values.


it("should be associative", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.anything(), fc.anything()),
          result(fc.anything(), fc.anything()),
          result(fc.anything(), fc.anything()),
          orAssociativity,
        ),
      );
    })

Summary: `orAssociativity` holds for three `result` objects with arbitrary values.


it("should fail to cast non-undefined", () => {
      expect.assertions(100);
      fc.assert(
        fc.property(
          fc.anything().filter((input) => typeof input !== "undefined"),
          (input) => {
            expect(castUndefined(input)).toStrictEqual({
              status: "failure",
              expected: "undefined",
              actual: input
            });
          }
        )
      );
    })

Summary: Casting a non-undefined value with `castUndefined` should return a failure status, indicating the expected type was "undefined."


it("should have a left annihilator", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(result(fc.anything(), fc.anything()), orLeftAnnihilation),
      );
    })

Summary: The `orLeftAnnihilation` property should hold for the `result` function applied to any two values, verifying the left annihilator property.


it("should agree with or", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.anything(), fc.anything()),
          result(fc.anything(), fc.anything()),
          orElseDefinition,
        ),
      );
    })

Summary: The property ensures that two `result` values agree with the `orElseDefinition`.


it("should agree with or", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.anything(), fc.anything()),
          result(fc.anything(), fc.anything()),
          orErstDefinition,
        ),
      );
    })

Summary: The test checks that the behavior of certain combinations of `result` values matches the expected behavior defined by `orErstDefinition`.


it("should have a left okay identity", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          fc.anything(),
          fc.func(result(fc.anything(), fc.anything())),
          flatMapLeftIdentityOkay,
        ),
      );
    })

Summary: The property verifies that applying `flatMapLeftIdentityOkay` with any value and a function on a `result` type maintains the left identity.


it("should have a left fail identity", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          fc.anything(),
          fc.func(result(fc.anything(), fc.anything())),
          flatMapLeftIdentityFail,
        ),
      );
    })

Summary: The property ensures that applying `flatMapLeftIdentityFail` maintains the identity when a failure is on the left.


it("should have a right okay and a right fail identity", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(result(fc.anything(), fc.anything()), flatMapRightIdentity),
      );
    })

Summary: The property checks that the `flatMapRightIdentity` function maintains the right identity on result objects for various inputs.


it("should be associative", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.anything(), fc.anything()),
          fc.func(result(fc.anything(), fc.anything())),
          fc.func(result(fc.anything(), fc.anything())),
          fc.func(result(fc.anything(), fc.anything())),
          fc.func(result(fc.anything(), fc.anything())),
          flatMapAssociativity,
        ),
      );
    })

Summary: The associativity property holds for operations involving `result` using functions generated by `flatMapAssociativity`.


it("should agree with flatMap", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.anything(), fc.anything()),
          fc.func(result(fc.anything(), fc.anything())),
          flatMapFailDefnition,
        ),
      );
    })

Summary: The `flatMapFailDefnition` should produce outcomes consistent with applying `flatMap` to results generated from arbitrary values and functions.


it("should agree with flatMapOkay", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(result(fc.anything(), fc.anything()), fc.anything()),
          flattenOkayDefinition,
        ),
      );
    })

Summary: `flattenOkayDefinition` should produce results that agree with the `flatMapOkay` operation on nested results.


it("should agree with flatMapFail", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.anything(), result(fc.anything(), fc.anything())),
          flattenFailDefinition,
        ),
      );
    })

Summary: The property asserts agreement between `flatMapFail` and `flattenFailDefinition` when applied to generated result structures.


it("should be equivalent to multiple flatMap calls", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.integer({ min: 1 }), fc.integer({ min: 1 })),
          fc.constant((n: number) => new Okay(collatz(n))),
          fc.constant((n: number) => new Fail(collatz(n))),
          flatMapUntilEquivalence,
        ),
      );
    })

Summary: The operation should be equivalent to applying multiple `flatMap` calls on a result with a minimum integer constraint.


it("should agree with isSomeAnd", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.anything(), fc.anything()),
          fc.func(fc.boolean()),
          isOkayAndDefinition,
        ),
      );
    })

Summary: The test ensures that a property holds true when comparing results processed by `isSomeAnd` and the `isOkayAndDefinition` function, using random data and boolean functions.


it("should agree with isNoneOr", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.anything(), fc.anything()),
          fc.func(fc.boolean()),
          isFailOrDefinition,
        ),
      );
    })

Summary: The property should ensure that behavior aligns with the `isNoneOr` function when tested with results from `fc.anything()` and a predicate function returning a boolean.


it("should agree with unzipWith", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.anything(), fc.anything()),
          fc.func(pair(fc.anything(), fc.anything())),
          unzipWithOkayDefinition,
        ),
      );
    })

Summary: The output from using `result` with arbitrary inputs and a function should match the output from `unzipWithOkayDefinition`.


it("should agree with unzipWith", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.anything(), pair(fc.anything(), fc.anything())),
          unzipFailDefinition,
        ),
      );
    })

Summary: The property checks that the `unzipFailDefinition` function consistently agrees with the behavior of `unzipWith` for various input pairs.


it("should be the inverse of associateLeft", () => {
      expect.assertions(100);

      fc.assert(
        fc.property(
          result(fc.anything(), result(fc.anything(), fc.anything())),
          associateRightInverse,
        ),
      );
    })

Summary: `associateRightInverse` applied to a result is the inverse of `associateLeft`.


it("should agree with gatherMapOkay", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          result(fc.anything(), fc.anything()),
          fc.func(task(fc.anything(), fc.anything())),
          groupMapLeftDefinition,
        ),
      );
    })

Summary: The function being tested should be consistent with `gatherMapOkay` when using combinations of `result`, `task`, and `groupMapLeftDefinition` functions.


it("should agree with gatherMapOkay", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          result(
            task(fc.anything(), fc.anything()),
            task(fc.anything(), fc.anything()),
          ),
          gatherOkayDefinition,
        ),
      );
    })

Summary: The test confirms that the `result` function aligns with the behavior defined by `gatherMapOkay` using asynchronous properties.


it("should agree with gatherMapOkay", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          result(task(fc.anything(), fc.anything()), fc.anything()),
          swapFailDefinition,
        ),
      );
    })

Summary: The test verifies that the outcome of a `result` function, using varying inputs, aligns with the behavior of `swapFailDefinition`.


it("should agree with gatherMapOkay", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          result(fc.anything(), task(fc.anything(), fc.anything())),
          groupLeftDefinition,
        ),
      );
    })

Summary: The function being tested should have consistent behavior with `gatherMapOkay` when applied to generated task results using `groupLeftDefinition`.


it("should agree with gatherMapFail", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          result(fc.anything(), fc.anything()),
          fc.func(task(fc.anything(), fc.anything())),
          swapMapOkayDefinition,
        ),
      );
    })

Summary: The property should ensure that `swapMapOkayDefinition` behaves consistently when compared against the behavior of `gatherMapFail`.


it("should agree with gatherMapFail", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          result(fc.anything(), fc.anything()),
          fc.func(task(fc.anything(), fc.anything())),
          groupMapRightDefinition,
        ),
      );
    })

Summary: The property should agree with `gatherMapFail` when comparing outputs using `result`, `func`, and `groupMapRightDefinition` functions.


it("should agree with gatherMapFail", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          result(
            task(fc.anything(), fc.anything()),
            task(fc.anything(), fc.anything()),
          ),
          gatherFailDefinition,
        ),
      );
    })

Summary: The function `result` should behave consistently with `gatherMapFail` when applied to tasks generated with arbitrary inputs.


it("should agree with gatherMapFail", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          result(fc.anything(), task(fc.anything(), fc.anything())),
          swapOkayDefinition,
        ),
      );
    })

Summary: `gatherMapFail` should produce results that agree with those generated by `swapOkayDefinition` when applied to asynchronous tasks and arbitrary values.


it("should agree with gatherMapFail", async () => {
      expect.assertions(100);

      await fc.assert(
        fc.asyncProperty(
          result(task(fc.anything(), fc.anything()), fc.anything()),
          groupRightDefinition,
        ),
      );
    })

Summary: The test ensures that the behavior of `result` with various tasks and values is consistent with `groupRightDefinition`.