it('should allow invalid values on validation: false', () => {
      fc.assert(
        fc.property(fc.anything(), (invalid) => {
          const blb = new DataAPIBlob(invalid as DataAPIBlobLike, false);
          assert.deepStrictEqual(blb.raw(), invalid);
        }),
      );
    })

Summary: The property ensures that `DataAPIBlob` created with `validation: false` retains the original invalid input value when calling `raw()`.


unknown

it('should get the byte length of all types', () => {
    fc.assert(
      fc.property(allBlobLikeArb, (bls) => {
        const expectedLength = bls[0].length;

        for (const blb of bls) {
          assert.strictEqual(blob(blb).byteLength, expectedLength);
          assert.strictEqual(blob(blob(blb)).byteLength, expectedLength);
        }
      }),
    );
  })

Summary: The byte length of all blob-like types should be consistent with the length of the first element in the array, even after being processed by the `blob` function.


it('should convert between compatible types in the browser', { pretendEnv: 'browser' }, () => {
    fc.assert(
      fc.property(allBlobLikeArb, ([buff, arrBuff, binary]) => {
        const blobs = [blob(buff), blob(arrBuff), blob(binary), blob(blob(buff))];

        for (const blb of blobs) {
          assert.strictEqual(blb.asBase64(), binary.$binary);
          assert.deepStrictEqual(blb.asBuffer(), buff);
          assert.deepStrictEqual(blb.asArrayBuffer(), arrBuff);
        }
      }),
    );
  })

Summary: Conversion between compatible types should preserve the correctness of Base64, Buffer, and ArrayBuffer representations.


it('should throw various conversion errors in unknown environments', { pretendEnv: 'unknown' }, () => {
    fc.assert(
      fc.property(allBlobLikeArb, ([buff, arrBuff, binary]) => {
        assert.throws(() => blob(buff).asBase64());
        assert.throws(() => blob(buff).asBuffer());
        assert.throws(() => blob(buff).asArrayBuffer());

        assert.throws(() => blob(arrBuff).asBase64());
        assert.throws(() => blob(arrBuff).asBuffer());
        assert.deepStrictEqual(blob(arrBuff).asArrayBuffer(), arrBuff);

        assert.deepStrictEqual(blob(binary).asBase64(), binary.$binary);
        assert.throws(() => blob(binary).asBuffer());
        assert.throws(() => blob(binary).asArrayBuffer());
      }),
    );
  })

Summary: The test verifies that various conversion methods on blob-like objects throw errors in unknown environments, with specific exceptions for `asArrayBuffer` and `asBase64` conversions under certain conditions.


it('should have a working toString()', () => {
    fc.assert(
      fc.property(allBlobLikeArb, ([buff, arrBuff, binary]) => {
        assert.strictEqual(blob(buff).toString(), `DataAPIBlob(typeof raw=Buffer, byteLength=${buff.length})`);
        assert.strictEqual(blob(arrBuff).toString(), `DataAPIBlob(typeof raw=ArrayBuffer, byteLength=${buff.length})`);
        assert.strictEqual(blob(binary).toString(), `DataAPIBlob(typeof raw=base64, byteLength=${buff.length})`);
        assert.strictEqual(blob(blob(binary)).toString(), `DataAPIBlob(typeof raw=base64, byteLength=${buff.length})`);
      }),
    );
  })

Summary: `blob` object's `toString()` method accurately represents the type and byte length of Buffer, ArrayBuffer, and base64 blob inputs.


it('should error if big numbers not enabled', () => {
    const serdes = new CollSerDes(CollSerDes.cfg.empty);

    fc.assert(
      fc.property(fc.bigInt(), (bigint) => {
        assert.throws(() => serdes.serialize({ bigint }), { message: 'BigInt serialization must be enabled through serdes.enableBigNumbers in CollectionSerDesConfig' });
      }),
    );

    fc.assert(
      fc.property(arbs.bigNum(), (bigint) => {
        assert.throws(() => serdes.serialize({ bigint }), { message: 'BigNumber serialization must be enabled through serdes.enableBigNumbers in CollectionSerDesConfig' });
      }),
    );
  })

Summary: Serialization of big numbers without enabling specific serialization settings results in an error.


Summary: Serialization should throw an error if big numbers serialization is not enabled in `CollSerDes`.


it('should error if no default * is specified for a CollNumCoercionCfg', () => {
    fc.assert(
      fc.property(arbs.record(fc.anything()), (spec) => {
        fc.pre(!('*' in spec));
        assert.throws(() => new CollSerDes({ ...CollSerDes.cfg.empty, enableBigNumbers: spec as any }), {
          message: 'The configuration must contain a "*" key',
        });
      }), {
        examples: [[{ a: { '*': 'bignumber' } }]],
      },
    );
  })

Summary: An error should be thrown if a `CollNumCoercionCfg` is created without a default `*` key specified in the configuration.


it('should handle to-number coercion properly', () => {
      const desAsserter = mkDesAsserter('number', Number);

      fc.assert(
        fc.property(fc.oneof(fc.double(), arbs.bigNum()), arbs.pathWithObj(), (num, pathWithObj) => {
          desAsserter.ok(pathWithObj, num);
        }),
      );
    })

Summary: `mkDesAsserter` ensures that numerical values, including large numbers, are properly coerced to the `number` type within given path and object structures.


it('should handle to-strict-number coercion properly', () => {
      const desAsserter = mkDesAsserter('strict_number', Number);

      fc.assert(
        fc.property(fc.double(), arbs.pathWithObj(), (num, pathWithObj) => {
          desAsserter.ok(pathWithObj, num);
        }),
      );

      fc.assert(
        fc.property(arbs.bigNum(), arbs.pathWithObj(), (bigNum, pathWithObj) => {
          if (bigNum.isEqualTo(bigNum.toNumber())) {
            desAsserter.ok(pathWithObj, bigNum);
          } else {
            desAsserter.notOk(pathWithObj, bigNum);
          }
        }),
      );
    })

Summary: `mkDesAsserter('strict_number', Number)` verifies that double values are coerced as expected, and checks whether big numbers can be accurately coerced to strict numbers based on their equality with their numeric representation.


Summary: `mkDesAsserter` properly handles coercion of numbers by passing finite doubles and big numbers when they can be represented as a strict number, and failing otherwise.


it('should handle to-bigint coercion properly', () => {
      const desAsserter = mkDesAsserter('bigint', (n) => BigInt(n.toFixed()));

      fc.assert(
        fc.property(fc.oneof(fc.integer(), fc.bigInt().map((n) => BigNumber(n.toString()))), arbs.pathWithObj(), (num, pathWithObj) => {
          desAsserter.ok(pathWithObj, num);
        }),
      );

      fc.assert(
        fc.property(fc.double(), arbs.pathWithObj(), (num, path) => {
          fc.pre(!Number.isInteger(num));
          desAsserter.notOk(path, num);
        }),
      );

      fc.assert(
        fc.property(arbs.bigNum(), arbs.pathWithObj(), (num, pathWithObj) => {
          fc.pre(!num.isInteger());
          desAsserter.notOk(pathWithObj, num);
        }),
      );
    })

Summary: Proper coercion of numeric values to `bigint` is confirmed, ensuring the conversion is correct for integers and identifying when it is not applicable for non-integers, including `double` and `bigNum` types.


Summary: The code ensures that converting numbers to `bigint` is handled correctly, with valid conversions passing `desAsserter.ok` and invalid conversions failing `desAsserter.notOk`.


it('should detect potential issues with the MusicPlayer', () =>
    fc.assert(
      fc.property(fc.uniqueArray(TrackNameArb, { minLength: 1 }), MusicPlayerCommands, (initialTracks, commands) => {
        // const real = new MusicPlayerImplem(initialTracks, true); // with bugs
        const real = new MusicPlayerImplem(initialTracks);
        const model = new MusicPlayerModel();
        model.numTracks = initialTracks.length;
        for (const t of initialTracks) {
          model.tracksAlreadySeen[t] = true;
        }
        fc.modelRun(() => ({ model, real }), commands);
      }),
    ))

Summary: The test checks that the operations run on a `MusicPlayerImplem` instance match the expected behavior as defined by the `MusicPlayerModel`, using a sequence of commands and initial tracks.


it('should always mark binary search trees as search trees', () => {
    fc.assert(
      fc.property(binarySearchTreeWithMaxDepth(3), (tree) => {
        return isSearchTree(tree);
      }),
    );
  })

Summary: Binary search trees with a maximum depth of 3 should always return true when verified by `isSearchTree`.


Summary: The test checks that `mkDesAsserter` correctly coerces integers and big integers to BigInt, ensuring non-integers (doubles and non-integer big numbers) do not pass coercion.


it('should handle to-string coercion properly', () => {
      const desAsserter = mkDesAsserter('string', (n) => n.toString());

      fc.assert(
        fc.property(fc.oneof(fc.double(), arbs.bigNum()), arbs.pathWithObj(), (num, pathWithObj) => {
          desAsserter.ok(pathWithObj, num);
        }),
      );
    })

Summary: The test checks that numbers, including doubles and big numbers, are correctly coerced to strings using the `mkDesAsserter` function when applied to paths within objects.


it('should detect invalid search trees whenever tree traversal produces unordered arrays', () => {
    fc.assert(
      fc.property(binaryTreeWithMaxDepth(3), (tree) => {
        fc.pre(!isSorted(traversal(tree, (t) => t.value)));
        return !isSearchTree(tree);
      }),
    );
  })

Summary: The test verifies that traversing a binary tree with unordered elements results in `isSearchTree` returning false.


it('should handle to-number_or_string coercion properly', () => {
      const desAsserterNum = mkDesAsserter('number_or_string', Number);
      const desAsserterStr = mkDesAsserter('number_or_string', (n) => n.toString());

      fc.assert(
        fc.property(fc.double(), arbs.pathWithObj(), (num, pathWithObj) => {
          desAsserterNum.ok(pathWithObj, num);
        }),
      );

      fc.assert(
        fc.property(arbs.bigNum(), arbs.pathWithObj(), (bigNum, pathWithObj) => {
          if (bigNum.isEqualTo(bigNum.toNumber())) {
            desAsserterNum.ok(pathWithObj, bigNum);
          } else {
            desAsserterStr.ok(pathWithObj, bigNum);
          }
        }),
      );
    })

Summary: The test checks that the `mkDesAsserter` function correctly coerces values to either numbers or strings depending on their representation and compatibility with JavaScript's number precision.


Summary: Coercion between numbers and strings is handled correctly based on the size and representation of the number.


it('should produce a non empty string', () => {
    fc.assert(
      fc.property(romanNumberArb, (n) => {
        expect(toRoman(n)).not.toBe('');
      }),
    );
  })

Summary: `toRoman` function produces a non-empty string for any input generated by `romanNumberArb`.


it('should be injective', () => {
    fc.assert(
      fc.property(romanNumberArb, romanNumberArb, (n1, n2) => {
        fc.pre(n1 !== n2);
        expect(toRoman(n2)).not.toBe(toRoman(n1));
      }),
    );
  })

Summary: `toRoman` function produces distinct outputs for different input values.


it('should allow a custom coercion function', () => {
      fc.assert(
        fc.property(fc.oneof(fc.double(), arbs.bigNum()), fc.anything(), arbs.pathWithObj(), (num, output, pathWithObj) => {
          const coerceFn = (n: number | BigNumber) => {
            assert.deepStrictEqual(n, num);
            return output;
          };

          const coerceFnAndTestPath = (n: number | BigNumber, path2: readonly PathSegment[]) => {
            assert.deepStrictEqual(pathWithObj[0], path2);
            return coerceFn(n);
          };

          mkDesAsserter(coerceFnAndTestPath, coerceFn).ok(pathWithObj, num);
        }),
      );
    })

Summary: A custom coercion function should correctly transform numbers or BigNumbers, while maintaining consistent path information.


it('should deserialize object ids properly', () => {
        fc.assert(
          fc.property(arbs.oid(), (objectId) => {
            assert.deepStrictEqual(serdes.deserialize({ $objectId: objectId.toString() }, {}), objectId);
          }),
        );
      })

Summary: The deserialization process should correctly convert `$objectId` strings back into their original object ID format.


it(`should error when trying to serialize a ${type}`, () => {
        fc.assert(
          fc.property(arb, (value) => {
            assert.throws(() => serdes.serialize(value), { message: new RegExp(`${type} may not be used with collections by default\\..*`) });
          }),
        );
      })

Summary: Serialization of a specific type should throw an error with a message indicating it cannot be used with collections by default.


it('inherits the keyspace from the db if not set', () => {
        const { db } = initTestObjects();

        fc.assert(
          fc.property(fc.string().filter(Boolean), (ks) => {
              db.useKeyspace(ks);
              const tsc = mkTSlashC(db, db._httpClient, 'tsc', opts, undefined);
              assert.strictEqual(tsc.keyspace, ks);
            },
          ),
        );
      })

Summary: If the keyspace is not specified, it should default to the keyspace set in the database.


it('works', () => {
        fc.assert(
          fc.property(fc.string(), fc.string(), (keyspace, name) => {
            const tsc = mkTSlashC(db, db._httpClient, name, opts, { keyspace });
            assert.strictEqual((tsc as any)[$CustomInspect](), `${cfg.className}(keyspace="${keyspace}",name="${name}")`);
          }),
        );
      })

Summary: The function `mkTSlashC` should produce an object that, when custom-inspected, outputs a string formatted as `className(keyspace="keyspace",name="name")`.


it('should function as a way to sneak ser/des implementations onto an existing class', () => {
    class Unsuspecting<T> {
      constructor(public readonly value: T) {}
    }

    (Unsuspecting.prototype as any)[$SerSym] = function (ctx: BaseSerCtx<unknown>) {
      return ctx.replace(this.value);
    };

    (Unsuspecting as any)[$DesSym] = function (_: string, ctx: BaseSerCtx<unknown>) {
      return ctx.mapAfter((v) => new Unsuspecting(v));
    };

    const UnsuspectingCodecClass = CodecsClass.asCodecClass(Unsuspecting);
    const UnsuspectingCodec = CodecsClass.forName('unsuspecting', UnsuspectingCodecClass);

    const serdes = new SerDesClass({ ...SerDesClass.cfg.empty, codecs: [UnsuspectingCodec] } as any);

    fc.assert(
      fc.property(cfg.datatypesArb({ count: 1 }), (datatypes) => {
        const unsuspecting = new Unsuspecting(datatypes[0].jsRep);

        const [actualSer] = serdes.serialize({ unsuspecting });
        assert.deepStrictEqual(actualSer, { unsuspecting: datatypes[0].jsonRep });

        const actualDes = serdes.deserialize(actualSer, desSchema({ unsuspecting: datatypes.definition! }));

        assert.deepStrictEqual(actualDes, { unsuspecting });
      }),
    );
  })

Summary: The test verifies that serialization and deserialization implementations can be dynamically attached to an existing class, ensuring they produce and consume the expected representations for the `Unsuspecting` class.


it('should accept a builder function to easily build implementations without typing as any', () => {
    class Unsuspecting<T> {
      constructor(public readonly value: T) {}
    }

    const UnsuspectingCodecClass = CodecsClass.asCodecClass(Unsuspecting, {
      serializeForTable(ctx) {
        return ctx.replace(this.value);
      },
      deserializeForTable(_, ctx) {
        return ctx.mapAfter((v) => new Unsuspecting(v));
      },
      serializeForCollection(ctx) {
        return ctx.replace(this.value);
      },
      deserializeForCollection(_, ctx) {
        return ctx.mapAfter((v) => new Unsuspecting(v));
      },
    });

    const UnsuspectingCodec = CodecsClass.forName('unsuspecting', UnsuspectingCodecClass);

    const serdes = new SerDesClass({ ...SerDesClass.cfg.empty, codecs: [UnsuspectingCodec] } as any);

    fc.assert(
      fc.property(cfg.datatypesArb({ count: 1 }), (datatypes) => {
        const unsuspecting = new Unsuspecting(datatypes[0].jsRep);

        const [actualSer] = serdes.serialize({ unsuspecting });
        assert.deepStrictEqual(actualSer, { unsuspecting: datatypes[0].jsonRep });

        const actualDes = serdes.deserialize(actualSer, desSchema({ unsuspecting: datatypes.definition! }));

        assert.deepStrictEqual(actualDes, { unsuspecting });
      }),
    );
  })

Summary: Accepts a builder function to create codec implementations, allowing serialization and deserialization of `Unsuspecting` objects without requiring `any` typing.


it('should throw an error if the "clazz" is not some function', () => {
    fc.assert(
      fc.property(fc.anything(), (clazz) => {
        fc.pre(typeof clazz !== 'function');
        assert.throws(() => CodecsClass.asCodecClass(clazz as any), TypeError);
      }),
    );
  })

Summary: An error is thrown if the input `clazz` is not a function when passed to `CodecsClass.asCodecClass`.


it('should throw an error when calling a builder method on a non-idle cursor', () => {
      const properties = <const>['filter', 'sort', 'limit', 'project', 'hybridLimits', 'rerankOn', 'map'] satisfies (keyof FindAndRerankCursor<unknown>)[];

      fc.assert(
        fc.property(fc.constantFrom(...properties), (builder) => {
          const cursor = new CursorImpl(parent, cfg.serdes, [{}, false]);
          cursor['_state'] = (Math.random() > .5) ? 'started' : 'closed';
          assert.throws(() => (cursor as any)[builder](), (e) => e instanceof CursorError && e.message.includes('on a running/closed cursor'));
        }),
      );
    })

Summary: An error should be thrown when invoking a builder method on a cursor that is not in the 'idle' state.


t.test('>>', t => {
  fc.assert(
    fc.property(fc.bigIntN(N), fc.bigIntN(15), (n, m) => {
      t.equal(t_shr(n, m), n >> m);
    }),
    {
      examples: [
        [1n, -1n],
        [-1n, 1n],
        [1n, 1n],
        [-1n, -1n],
        [0xdeadbeefn, 1n],
        [0xdeadbeefn, 8n],
        [0xdeadbeefn, 32n],
        [0xdeadbeefn, 64n],
        [-0xdeadbeefn, 64n]
      ]
    }
  );

  t.end();
})

Summary: `t_shr` function should produce the same result as the native bitwise right shift operation for given big integers `n` and `m`.


it('should create a new cursor with a new pre-serialized sort', () => {
        fc.assert(
          fc.property(arbs.record(fc.anything()), arbs.record(fc.anything()), (sort, oldOptions) => {
            const cursor = new CursorImpl(parent, cfg.serdes, [{}, false], oldOptions);

            const newSort = cfg.serdes.serialize(sort, SerDesTarget.Sort)[0];

            CursorInternalDeltaAsserter
              .captureImmutDelta(cursor._internal, () => cursor.sort(sort as unknown as HybridSort)._internal)
              .assertDelta({ _options: { ...oldOptions, sort: newSort } });
          }),
        );
      })

Summary: A new cursor should be created with an updated pre-serialized sort, maintaining immutability and correctly reflecting changes in internal options.


it('should create a new cursor with a new limit', () => {
        fc.assert(
          fc.property(fc.nat(), arbs.record(fc.anything()), (limit, oldOptions) => {
            const cursor = new CursorImpl(parent, null!, [{}, false], oldOptions);

            CursorInternalDeltaAsserter
              .captureImmutDelta(cursor._internal, () => cursor.limit(limit)._internal)
              .assertDelta({ _options: { ...oldOptions, limit: limit || undefined } });
          }),
        );
      })

Summary: `CursorImpl` generates a new cursor reflecting an updated limit without altering other options.


it('should create a new cursor with a new projection', () => {
        fc.assert(
          fc.property(arbs.record(fc.oneof(fc.constantFrom(0, 1), fc.boolean())), arbs.record(fc.anything()), (projection, oldOptions) => {
            const cursor = new CursorImpl(parent, null!, [{}, false], oldOptions);

            CursorInternalDeltaAsserter
              .captureImmutDelta(cursor._internal, () => cursor.project(projection)._internal)
              .assertDelta({ _options: { ...oldOptions, projection } });
          }),
        );
      })

Summary: A new cursor should be created with an updated projection, verifying the internal state change reflects the new projection while retaining other options.


it('should create a new cursor with new hybrid limits', () => {
        fc.assert(
          fc.property(fc.oneof(fc.nat(), arbs.record(fc.nat())), arbs.record(fc.anything()), (limits, oldOptions) => {
            const cursor = new CursorImpl(parent, null!, [{}, false], oldOptions);

            CursorInternalDeltaAsserter
              .captureImmutDelta(cursor._internal, () => cursor.hybridLimits(limits)._internal)
              .assertDelta({ _options: { ...oldOptions, hybridLimits: limits } });
          }),
        );
      })

Summary: `CursorImpl` creates a new cursor with updated hybrid limits, ensuring that the internal options reflect these changes.


it('should create a new cursor with new rerankOn configuration', () => {
        fc.assert(
          fc.property(fc.string(), arbs.record(fc.anything()), (rerankField, oldOptions) => {
            const cursor = new CursorImpl(parent, null!, [{}, false], oldOptions);

            CursorInternalDeltaAsserter
              .captureImmutDelta(cursor._internal, () => cursor.rerankOn(rerankField)._internal)
              .assertDelta({ _options: { ...oldOptions, rerankOn: rerankField } });
          }),
        );
      })

Summary: Creating a new cursor should update the `rerankOn` field in `_options` with the new configuration while retaining other existing options.


it('should create a new cursor with new rerankQuery configuration', () => {
        fc.assert(
          fc.property(fc.string(), arbs.record(fc.anything()), (rerankQuery, oldOptions) => {
            const cursor = new CursorImpl(parent, null!, [{}, false], oldOptions);

            CursorInternalDeltaAsserter
              .captureImmutDelta(cursor._internal, () => cursor.rerankQuery(rerankQuery)._internal)
              .assertDelta({ _options: { ...oldOptions, rerankQuery: rerankQuery } });
          }),
        );
      })

Summary: Creating a new cursor with a `rerankQuery` updates the `_options` configuration while ensuring immutability.


it('should create a new cursor with new includeScores configuration', () => {
        fc.assert(
          fc.property(fc.boolean(), arbs.record(fc.anything()), (includeScores, oldOptions) => {
            const cursor = new CursorImpl(parent, null!, [{}, false], oldOptions);

            CursorInternalDeltaAsserter
              .captureImmutDelta(cursor._internal, () => cursor.includeScores(includeScores)._internal)
              .assertDelta({ _options: { ...oldOptions, includeScores: includeScores } });
          }),
        );
      })

Summary: Creating a new cursor should update the `_options` property to include a new `includeScores` configuration.


it('should create a new cursor with sort vector included', () => {
        fc.assert(
          fc.property(fc.constantFrom(undefined, true, false), arbs.record(fc.anything()), (include, oldOptions) => {
            const cursor = new CursorImpl(parent, null!, [{}, false], oldOptions);

            CursorInternalDeltaAsserter
              .captureImmutDelta(cursor._internal, () => cursor.includeSortVector(include)._internal)
              .assertDelta({ _options: { ...oldOptions, includeSortVector: include ?? true } });
          }),
        );
      })

Summary: Including a sort vector in the creation of a new cursor properly updates the internal options with the `includeSortVector` flag.


it('should create a new cursor with the initial page state set if a string', () => {
        fc.assert(
          fc.property(fc.string(), arbs.record(fc.anything()), (pageState, oldOptions) => {
            const cursor = new CursorImpl(parent, null!, [{}, false], oldOptions);

            CursorDeltaAsserter
              .captureImmutDelta(cursor, () => cursor.initialPageState(pageState))
              .assertDelta({ _currentPage: { nextPageState: pageState, result: [] } });
          }),
        );
      })

Summary: Creating a new cursor sets the initial page state with a given string, verifying that `_currentPage.nextPageState` is updated correctly.


it('should error if initialPageState is null', () => {
        fc.assert(
          fc.property(arbs.record(fc.anything()), (oldOptions) => {
            const cursor = new CursorImpl(parent, null!, [{}, false], oldOptions);

            assert.throws(() => cursor.initialPageState(null!), (e) => {
              return e instanceof CursorError && e.message.includes('Cannot set an initial page state to `null`');
            });
          }),
        );
      })

Summary: An error is thrown when `initialPageState` is set to `null` in `CursorImpl`.


it('works', () => {
        fc.assert(
          fc.property(arbs.cursorState(), fc.nat(), fc.nat(), (state, consumed, buffered) => {
            const cursor = new CursorImpl(parent, null!, [{}, false]);
            cursor['_state'] = state;
            cursor['_consumed'] = consumed;
            cursor['_currentPage'] = { nextPageState: null, result: new Array(buffered) };

            assert.strictEqual((cursor as any)[$CustomInspect](), `${CursorImpl.name}(source="${parent.keyspace}.${parent.name}",state="${state}",consumed=${consumed},buffered=${buffered})`);
          }),
        );
      })

Summary: The `CursorImpl` object's custom inspection string representation includes its source, state, consumed count, and buffered count, formatted correctly.


it('should throw an error when calling a builder method on a non-idle cursor', () => {
      const properties = <const>['filter', 'sort', 'limit', 'skip', 'project', 'includeSimilarity', 'includeSortVector', 'map'] satisfies (keyof FindCursor<unknown>)[];

      fc.assert(
        fc.property(fc.constantFrom(...properties), (builder) => {
          const cursor = new CursorImpl(parent, cfg.serdes, [{}, false]);
          cursor['_state'] = (Math.random() > .5) ? 'started' : 'closed';
          assert.throws(() => (cursor as any)[builder](), (e) => e instanceof CursorError && e.message.includes('on a running/closed cursor'));
        }),
      );
    })

Summary: Calling a builder method on a non-idle cursor should throw a `CursorError` indicating the cursor is running or closed.


it('should create a new cursor with a new pre-serialized sort', () => {
        fc.assert(
          fc.property(arbs.record(fc.anything()), arbs.record(fc.anything()), (sort, oldOptions) => {
            const cursor = new CursorImpl(parent, cfg.serdes, [{}, false], oldOptions);

            const newSort = cfg.serdes.serialize(sort, SerDesTarget.Sort)[0];

            CursorInternalDeltaAsserter
              .captureImmutDelta(cursor._internal, () => cursor.sort(sort as Sort)._internal)
              .assertDelta({ _options: { ...oldOptions, sort: newSort } });
          }),
        );
      })

Summary: A new cursor should be created with an updated pre-serialized sort, ensuring the internal options reflect this change while maintaining immutability.


Summary: Creating a new cursor should update its `_options` with the specified limit, preserving other options.


it('should create a new cursor with a new skip', () => {
        fc.assert(
          fc.property(fc.nat(), arbs.record(fc.anything()), (skip, oldOptions) => {
            const cursor = new CursorImpl(parent, null!, [{}, false], oldOptions);

            CursorInternalDeltaAsserter
              .captureImmutDelta(cursor._internal, () => cursor.skip(skip)._internal)
              .assertDelta({ _options: { ...oldOptions, skip } });
          }),
        );
      })

Summary: A new cursor, when given a skip value, should update its internal options to reflect the new skip while preserving other options.


it('should create a new cursor with similarity included', () => {
        fc.assert(
          fc.property(fc.constantFrom(undefined, true, false), arbs.record(fc.anything()), (include, oldOptions) => {
            const cursor = new CursorImpl(parent, null!, [{}, false], oldOptions);

            CursorInternalDeltaAsserter
              .captureImmutDelta(cursor._internal, () => cursor.includeSimilarity(include)._internal)
              .assertDelta({ _options: { ...oldOptions, includeSimilarity: include ?? true } });
          }),
        );
      })

Summary: A new cursor should be created with the similarity option included, ensuring the internal state reflects this change based on the provided options.


it('should return a brand new cursor with the same config', () => {
        const allArbs = <const>[
          arbs.record(fc.anything()),
          arbs.record(fc.anything()),
          fc.func(fc.anything()),
          fc.array(fc.anything()),
          arbs.cursorState(),
          fc.nat(),
          fc.string(),
        ];

        fc.assert(
          fc.property(...allArbs, (filter, options, mapping, buffer, state, consumed, qs) => {
            const cursor = new CursorImpl(parent, null!, [filter, false], options, mapping);

            cursor['_currentPage'] = { nextPageState: qs, result: buffer };
            cursor['_state'] = state;
            cursor['_consumed'] = consumed;

            CursorDeltaAsserter
              .captureImmutDelta(cursor, () => {
                return cursor.clone();
              })
              .assertDelta({
                _currentPage: undefined,
                _state: 'idle',
                _consumed: 0,
              });
          }),
        );
      })

Summary: Cloning a cursor should produce a new cursor with reset properties, maintaining the original configuration but setting `_currentPage` to undefined, `_state` to 'idle', and `_consumed` to 0.


Summary: The custom inspect method of `CursorImpl` should return a string representation that includes the source, state, consumed, and buffered values of the cursor.


it('should return the length of cursor._currentPage.result', () => {
        fc.assert(
          fc.property(fc.nat(), (count) => {
            const cursor = new CursorImpl(parent, null!, [{}, false]);
            cursor['_currentPage'] = { nextPageState: null, result: Array(count) };
            assert.strictEqual(cursor.buffered(), count);
          }),
        );
      })

Summary: The `buffered` method should return the length of the `result` array in `cursor._currentPage`.


it('should consume all docs & increase consumed() if no max parameter passed', () => {
        fc.assert(
          fc.property(fc.array(fc.anything()), (buffer) => {
            const cursor = new CursorImpl(parent, null!, [{}, false]);
            cursor['_currentPage'] = { nextPageState: null, result: [...buffer] as SomeDoc[] };

            assert.strictEqual(cursor.consumed(), 0);
            assert.strictEqual(cursor.buffered(), buffer.length);

            DeltaAsserter
              .captureMutDelta(cursor, () => {
                const consumed = cursor.consumeBuffer();
                assert.deepStrictEqual(consumed, buffer);
              })
              .assertDelta({
                _consumed: buffer.length,
                _currentPage: { nextPageState: null, result: [] },
              });

            assert.strictEqual(cursor.consumed(), buffer.length);
            assert.strictEqual(cursor.buffered(), 0);
          }),
        );
      })

Summary: The cursor should consume all documents, increasing the consumed count, when no max parameter is specified.


it('should consume the max docs possible & increase consumed() if max parameter passed', () => {
        fc.assert(
          fc.property(fc.array(fc.anything()), fc.nat(), (buffer, max) => {
            const cursor = new CursorImpl(parent, null!, [{}, false]);
            cursor['_currentPage'] = { nextPageState: null, result: [...buffer] as SomeDoc[] };

            assert.strictEqual(cursor.consumed(), 0);
            assert.strictEqual(cursor.buffered(), buffer.length);

            const expectedConsumed = Math.min(buffer.length, max);

            DeltaAsserter
              .captureMutDelta(cursor, () => {
                const consumed = cursor.consumeBuffer(max);
                assert.deepStrictEqual(consumed, buffer.slice(0, expectedConsumed));
              })
              .assertDelta({
                _consumed: expectedConsumed,
                _currentPage: { nextPageState: null, result: buffer.slice(expectedConsumed) },
              });

            assert.strictEqual(cursor.consumed(), expectedConsumed);
            assert.strictEqual(cursor.buffered(), buffer.length - expectedConsumed);
          }),
        );
      })

Summary: The cursor should consume up to a maximum number of documents from the buffer, updating its consumed count accordingly, when a max parameter is specified.


it('should reset the state, consumed count, currentPage, and isNextPage', () => {
        fc.assert(
          fc.property(fc.array(fc.anything()), fc.integer(), fc.option(fc.string()), fc.constantFrom('idle', 'started', 'closed'), (buffer, consumed, qs, state) => {
            const cursor = new CursorImpl(parent, null!, [{}, false]);
            cursor['_currentPage'] = { nextPageState: qs, result: [...buffer] as SomeDoc[] };
            cursor['_consumed'] = consumed;
            cursor['_state'] = state;
            cursor['_isNextPage'] = false;

            assert.strictEqual(cursor.state, state);
            assert.strictEqual(cursor.buffered(), buffer.length);
            assert.strictEqual(cursor.consumed(), consumed);

            DeltaAsserter
              .captureMutDelta(cursor, () => {
                cursor.rewind();
              })
              .assertDelta({
                _state: 'idle',
                _consumed: 0,
                _currentPage: undefined,
                _isNextPage: true,
              });

            assert.strictEqual(cursor.state, 'idle');
            assert.strictEqual(cursor.buffered(), 0);
            assert.strictEqual(cursor.consumed(), 0);
          }),
        );
      })

Summary: The `rewind` method resets the cursor's state to 'idle', sets consumed count to 0, clears the current page, and sets `isNextPage` to true.


it('should reset the buffer but not consumed', () => {
        fc.assert(
          fc.property(fc.array(fc.anything()), fc.integer(), (buffer, consumed) => {
            const cursor = new CursorImpl(parent, null!, [{}, false]);
            cursor['_currentPage'] = { nextPageState: null, result: [...buffer] as SomeDoc[] };
            cursor['_consumed'] = consumed;

            assert.strictEqual(cursor.buffered(), buffer.length);
            assert.strictEqual(cursor.consumed(), consumed);

            DeltaAsserter
              .captureMutDelta(cursor, () => {
                cursor.close();
              })
              .assertDelta({
                _state: 'closed',
                _currentPage: undefined,
              });

            assert.strictEqual(cursor.buffered(), 0);
            assert.strictEqual(cursor.consumed(), consumed);
          }),
        );
      })

Summary: Resetting the buffer on `CursorImpl` should not affect the `consumed` count after closing the cursor, ensuring that only the `_state` and `_currentPage` change.


it('should ser/des keys with matching names', () => {
    const arb = fc.jsonValue({ depthSize: 'medium' })
      .filter((val) => !!val && typeof val === 'object')
      .filter((val) => Object.keys(val).length > 0)
      .chain((val) => {
        return fc.tuple(fc.constant(val), fc.constantFrom(...Object.keys(val)));
      });

    fc.assert(
      fc.property(arb, ([obj, targetKey]) => {
        const codec = CodecsClass.forName(targetKey, {
          serialize: (v: any, ctx: BaseSerDesCtx) => ctx.done(JSON.stringify(v)),
          deserialize: (v: any, ctx: BaseSerDesCtx) => ctx.done(JSON.stringify(v)),
        });

        const serdes = mkSerDesWithCodecs([codec]);

        const expectedObj = structuredClone(obj);
        traverseObject(expectedObj, (obj, key) => {
          fc.pre(key !== '');

          if (String(key) === targetKey) {
            obj[key] = JSON.stringify(obj[key]);
          }
        });

        assert.deepStrictEqual(serdes.serialize(obj), [expectedObj, false]);
        assert.deepStrictEqual(serdes.deserialize(obj, { status: { projectionSchema: {} } }), expectedObj);
      }),
    );
  })

Summary: Keys matching their name are serialized and deserialized correctly using specified codecs.


it('should not do anything when returning ctx.nevermind()', () => {
    const arb = arbs.jsonObj()
      .filter((val) => Object.keys(val).length > 0)
      .chain((val) => {
        return fc.tuple(fc.constant(val), fc.constantFrom(...Object.keys(val)));
      });

    fc.assert(
      fc.property(arb, fc.integer({ min: 1, max: 100 }), ([obj, targetKey], numCodecs) => {
        const matchingValuesSet = new Set<any>();
        let expectMatched = 0, matchedSer = 0, matchedDes = 0;

        const codec = CodecsClass.forName(targetKey, {
          serialize(v: any, ctx: BaseSerDesCtx) {
            assert.ok(matchingValuesSet.has(v));
            matchedSer++;
            return ctx.nevermind();
          },
          deserialize(v: any, ctx: BaseSerDesCtx) {
            assert.ok(matchingValuesSet.has(v));
            matchedDes++;
            return ctx.nevermind();
          },
        });

        const serdes = mkSerDesWithCodecs(Array(numCodecs).fill(codec));

        traverseObject(obj, (obj, key) => {
          fc.pre(key !== '');

          if (String(key) === targetKey) {
            matchingValuesSet.add(obj[key]);
            expectMatched++;
          }
        });

        assert.deepStrictEqual(serdes.serialize(obj), [obj, false]);
        assert.deepStrictEqual(serdes.deserialize(obj, { status: { projectionSchema: {} } }), obj);
        assert.ok(matchingValuesSet.size > 0);
        assert.ok(expectMatched >= matchingValuesSet.size);
        assert.strictEqual(matchedSer, expectMatched * numCodecs);
        assert.strictEqual(matchedDes, expectMatched * numCodecs);
      }),
    );
  })

Summary: Verifies that when using `ctx.nevermind()` in serialization and deserialization, the operation effectively results in the original object being returned without alteration, ensuring correct serialization and deserialization counts match expectations.


it('should be associative', () => {
    fc.assert(
      fc.property(valueArb, valueArb, valueArb, (a, b, c) => {
        assert.deepStrictEqual(
          handler.concat([a, handler.concat([b, c])]),
          handler.concat([handler.concat([a, b]), c]),
        );
      }),
    );
  })

Summary: The concatenation operation should be associative.


t.test('factorials', t => {
  fc.assert(
    fc.property(fc.integer({ min: 5, max: N }), n => {
      t.equal(t_fact(n), BigIntMath.fact(BigInt(n)));
    }),
    {
      examples: [[0], [1], [10], [100], [1000]]
    }
  );

  t.end();
})

Summary: The test verifies that the `t_fact` function produces the same result as `BigIntMath.fact` for integers between 5 and a specified maximum, including specific cases like 0, 1, 10, 100, and 1000.


it('should follow identity laws', () => {
    fc.assert(
      fc.property(valueArb, (layer) => {
        assert.deepStrictEqual(handler.concat([layer, handler.empty]), layer);
        assert.deepStrictEqual(handler.concat([handler.empty, layer]), layer);
      }),
    );
    assert.deepStrictEqual(handler.concat([handler.empty, handler.empty]), handler.empty);
  })

Summary: Concatenating a value with an empty element should return the original value, and concatenating two empty elements should return an empty element.


test('pass', () => {
      fc.assert(
        fc.property(fc.anything(), (actual) => {
          return Match.ANY(actual);
        }),
      );
    })

Summary: `Match.ANY` should return true for any input value.


test('pass', () => {
      fc.assert(
        fc.property(
          fc
            .array(fc.oneof(fc.string(), fc.integer(), fc.float()), {
              minLength: 1,
            })
            .chain((allowed) => fc.tuple(fc.constant(allowed), fc.constantFrom(...allowed))),
          ([allowed, actual]) => {
            return Match.oneOf(...allowed)(actual);
          },
        ),
      );
    })

Summary: `Match.oneOf` returns true for an `actual` value that is included in the `allowed` array.


test('fail', () => {
      fc.assert(
        fc.property(
          fc.uniqueArray(fc.oneof(fc.string(), fc.integer(), fc.float()), {
            minLength: 1,
          }),
          (possible) => {
            const allowed = possible.slice(0, -1);
            const actual = possible.at(-1);
            return !Match.oneOf(...allowed)(actual, {
              reporter: expectViolation('Expected value to be one of', allowed, actual),
            });
          },
        ),
      );
    })

Summary: The test verifies that if the last element of a unique array is not in the preceding elements, `Match.oneOf` will correctly trigger a violation message indicating the actual value was not expected.


test('pass', () => {
      fc.assert(
        fc.property(fc.anything(), (value) => {
          return Match.eq(value)(value);
        }),
      );
    })

Summary: Evaluates that `Match.eq` correctly identifies any value as equal to itself.


test('fail', () => {
      fc.assert(
        fc.property(
          fc.uniqueArray(
            // Need to remove empty arrays here as they are equal to each other
            fc.anything(),
            {
              minLength: 2,
              maxLength: 2,
              // mimic what the matcher does
              // this uses loose equality, while catching any not comparable values
              comparator: (a, b) => {
                try {
                  return a == b || Match.arrEq(a as any)(b);
                } catch {
                  return false;
                }
              },
            },
          ),
          ([expected, actual]) => {
            const keyword = Array.isArray(expected) ? 'array' : 'value';
            return !Match.eq(expected)(actual, { reporter: expectViolation(`Expected ${keyword}`, expected, actual) });
          },
        ),
      );
    })

Summary: Ensures that when two unique, non-identical values or arrays are compared using `Match.eq`, the comparison fails, triggering the `expectViolation` function to validate the message content.


test('pass', () => {
      fc.assert(
        fc.property(
          fc
            .array(arrayEl)
            .chain((expected) =>
              fc.tuple(
                fc.constant(expected),
                fc.shuffledSubarray(expected, { minLength: expected.length, maxLength: expected.length }),
              ),
            ),
          ([expected, actual]) => {
            return Match.arrEq(expected)(actual);
          },
        ),
      );
    })

Summary: `Match.arrEq` confirms that a shuffled subarray of `expected` with the same length is equal to `expected`.


test('fail', () => {
      fc.assert(
        fc.property(
          fc.uniqueArray(arrayEl, {
            minLength: 1,
          }),
          fc.array(arrayEl),
          (possible, actualBase) => {
            const expected = possible.slice(0, -1);
            const actual = [...actualBase, possible.at(-1)];
            return !Match.arrEq(expected)(actual, {
              reporter: expectViolation('Expected array matching', expected, actual),
            });
          },
        ),
      );
    })

Summary: The property ensures that when an array is created by appending an element from a unique array, a mismatch is detected between the expected and actual arrays using a custom reporting function.


test('pass', () => {
      fc.assert(
        fc.property(fc.string(), (value) => {
          return Match.strEq(value, true)(value);
        }),
      );
    })

Summary: `Match.strEq` should return true when the input string is compared to itself.


test('pass', () => {
      fc.assert(
        fc.property(
          fc.string({ minLength: 1 }).chain((s) => fc.tuple(fc.constant(s), fc.mixedCase(fc.constant(s)))),
          ([expected, actual]) => {
            return Match.strEq(expected, false)(actual);
          },
        ),
      );
    })

Summary: `Match.strEq` should return true when comparing a string with its mixed-case variant.


test('fail', () => {
      fc.assert(
        fc.property(
          fc.uniqueArray(fc.string(), {
            minLength: 2,
            maxLength: 2,
          }),
          ([expected, actual]) => {
            return !Match.strEq(expected, true)(actual, {
              reporter: expectViolation('Expected string', expected, actual),
            });
          },
        ),
      );
    })

Summary: The test ensures that `Match.strEq` correctly identifies strings as different when they are not equal, triggering `expectViolation` with a specific error message that includes both strings.


test('fail', () => {
      fc.assert(
        fc.property(
          fc.anything().filter((v) => !(v === undefined || v === null)),
          (actual) => {
            return !Match.MISSING(actual);
          },
        ),
      );
    })

Summary: `Match.MISSING` should not return true for any value that is not `undefined` or `null`.


test('throws for non objects', () => {
    fc.assert(
      fc.property(fc.oneof(fc.anything({ maxDepth: 0 }), fc.array(fc.anything())), (data: any) => {
        const validator = new ObjectValidator(new RuleSet(), 'testData');
        expect(() => validator.validate(data)).toThrow('Provided data must be an object');
      }),
    );
  })

Summary: Validates that the `ObjectValidator` throws an error if the input data is not an object.


test('strict', () => {
    fc.assert(
      fc.property(
        fcTsconfig({
          compilerRuleSet: rulesForStrict,
        }),
        (config) => {
          const validator = new TypeScriptConfigValidator(TypeScriptConfigValidationRuleSet.STRICT);
          validator.validate(config);
        },
      ),
    );
  })

Summary: Validating that a TypeScript configuration adheres to the `STRICT` rule set using a `TypeScriptConfigValidator`.


it('Should always generate values within the range [from ; to]', () =>
    fc.assert(
      fc.property(fc.noShrink(fc.integer()), fc.maxSafeInteger(), fc.maxSafeInteger(), (seed, a, b) => {
        const [from, to] = a < b ? [a, b] : [b, a];
        const [v, _nrng] = uniformIntDistribution(from, to)(mersenne(seed));
        return v >= from && v <= to;
      }),
    ))

Summary: Generated values should always fall within the specified inclusive range \([from; to]\) using `uniformIntDistribution`.


it('Should always generate values within the range [from ; to]', () =>
    fc.assert(
      fc.property(fc.noShrink(fc.integer()), arrayIntArb(), arrayIntArb(), (seed, a, b) => {
        const [from, to] = arrayIntToBigInt(a) < arrayIntToBigInt(b) ? [a, b] : [b, a];
        const [v, _nrng] = uniformArrayIntDistribution(from, to)(mersenne(seed));
        const vBigInt = arrayIntToBigInt(v);
        return vBigInt >= arrayIntToBigInt(from) && vBigInt <= arrayIntToBigInt(to);
      }),
    ))

Summary: Generated values from `uniformArrayIntDistribution` should lie within the range defined by two `ArrayInt` values converted to `BigInt`.


it('Should always trim the zeros from the resulting value', () =>
    fc.assert(
      fc.property(fc.noShrink(fc.integer()), arrayIntArb(), arrayIntArb(), (seed, a, b) => {
        const [from, to] = arrayIntToBigInt(a) < arrayIntToBigInt(b) ? [a, b] : [b, a];
        const [v, _nrng] = uniformArrayIntDistribution(from, to)(mersenne(seed));
        expect(v.data).not.toHaveLength(0);
        if (v.data.length !== 1) {
          expect(v.data[0]).not.toBe(0); // do not start by zero when data has multiple values
        } else if (v.data[0] === 0) {
          expect(v.sign).toBe(1); // zero has sign=1
        }
      }),
    ))

Summary: The resulting value from `uniformArrayIntDistribution` should not have leading zeros in its data array, and if it's zero, the sign should be positive.


it('Should always produce valid ArrayInt', () =>
    fc.assert(
      fc.property(fc.noShrink(fc.integer()), arrayIntArb(), arrayIntArb(), (seed, a, b) => {
        const [from, to] = arrayIntToBigInt(a) < arrayIntToBigInt(b) ? [a, b] : [b, a];
        const [v, _nrng] = uniformArrayIntDistribution(from, to)(mersenne(seed));
        expect([-1, 1]).toContainEqual(v.sign); // sign is either 1 or -1
        expect(v.data).not.toHaveLength(0); // data is never empty
        for (const d of v.data) {
          // data in [0 ; 0xffffffff]
          expect(d).toBeGreaterThanOrEqual(0);
          expect(d).toBeLessThanOrEqual(0xffffffff);
        }
      }),
    ))

Summary: The test checks that `uniformArrayIntDistribution` generates non-empty `ArrayInt` values with a sign of either 1 or -1, and data elements within the range [0, 0xffffffff].


test("sign and verify should be symmetric operations", async () => {
			await fc.assert(
				fc.asyncProperty(validPayloadArb, validKeyArb, async (payload, key) => {
					// Create a token with a key ID
					const token = await JWT.sign({
						payload,
						key,
						header: { kid: "test-key-prop" },
					});

					// Create a JWK Set with the key
					const jwkSet: JWKKeySet = {
						keys: [
							{
								kty: "oct",
								k: base64Url.encode(new TextEncoder().encode(key)),
								kid: "test-key-prop",
								alg: "HS256",
								use: "sig",
							},
						],
					};

					const result = await JWT.verify({
						token,
						key: jwkSet,
						audience: payload.aud,
						issuer: payload.iss,
					});
					return result.valid && result.payload.sub === payload.sub;
				}),
				{ numRuns: 10 }, // Limit runs for test performance
			);
		})

Summary: Signing and verifying a JWT should be symmetric, ensuring that the verified token is valid and its subject matches the original payload.


test("encrypt and decrypt should be symmetric operations", async () => {
			await fc.assert(
				fc.asyncProperty(validPayloadArb, validKeyArb, async (payload, key) => {
					const token = await JWT.encrypt({ payload, key });
					const result = await JWT.decrypt({
						token,
						key,
						audience: payload.aud,
						issuer: payload.iss,
					});
					return result.valid && result.payload.sub === payload.sub;
				}),
				{ numRuns: 10 }, // Limit runs for test performance
			);
		})

Summary: Encrypting and then decrypting a payload with a key should result in a valid output with the same subject.


test("should encrypt and decrypt arbitrary payloads", async () => {
		await fc.assert(
			fc.asyncProperty(
				fc.object({
					maxDepth: 2,
					key: fc.string(),
					values: [fc.string(), fc.integer(), fc.boolean()],
				}),
				fc.string(),
				async (arbitraryPayload, arbitraryKey) => {
					// Skip empty keys
					if (!arbitraryKey) return true;

					const payload = { ...arbitraryPayload } as StandardClaims;
					const token = await JWE.encrypt({ payload, key: arbitraryKey });
					const decrypted = await JWE.decrypt({ token, key: arbitraryKey });

					return JSON.stringify(decrypted.payload) === JSON.stringify(payload);
				},
			),
			{ numRuns: 10 }, // Limit runs for performance
		);
	})

Summary: Encrypting and then decrypting arbitrary payloads with a non-empty key should yield an equivalent payload.


test("should fail decryption with wrong key", async () => {
		await fc.assert(
			fc.asyncProperty(
				fc.object(),
				fc.string({ minLength: 1 }),
				fc.string({ minLength: 1 }),
				async (arbitraryPayload, correctKey, wrongKey) => {
					// Skip if keys are the same
					if (correctKey === wrongKey) return true;

					const payload = { ...arbitraryPayload } as StandardClaims;
					const token = await JWE.encrypt({ payload, key: correctKey });

					try {
						await JWE.decrypt({ token, key: wrongKey });
						return false; // Should not succeed
					} catch (error) {
						return true; // Expected to fail
					}
				},
			),
			{ numRuns: 10 }, // Limit runs for performance
		);
	})

Summary: Decryption should fail when a token encrypted with a correct key is attempted to be decrypted with a different, incorrect key.


test("should sign and verify arbitrary payloads", async () => {
		await fc.assert(
			fc.asyncProperty(
				fc.object({
					maxDepth: 2,
					key: fc.string(),
					values: [fc.string(), fc.integer(), fc.boolean()],
				}),
				fc.string({ minLength: 1 }),
				async (arbitraryPayload, arbitraryKey) => {
					const payload = { ...arbitraryPayload } as StandardClaims;
					const token = await JWS.sign({ payload, key: arbitraryKey });
					const verified = await JWS.verify({ token, key: arbitraryKey });

					return JSON.stringify(verified) === JSON.stringify(payload);
				},
			),
			{ numRuns: 10 }, // Limit runs for performance
		);
	})

Summary: Signing and verifying arbitrary payloads with a given key should result in the verified payload matching the original payload.


test("should fail verification with wrong key", async () => {
		await fc.assert(
			fc.asyncProperty(
				fc.object(),
				fc.string({ minLength: 1 }),
				fc.string({ minLength: 1 }),
				async (arbitraryPayload, correctKey, wrongKey) => {
					// Skip if keys are the same
					if (correctKey === wrongKey) return true;

					const payload = { ...arbitraryPayload } as StandardClaims;
					const token = await JWS.sign({ payload, key: correctKey });

					try {
						await JWS.verify({ token, key: wrongKey });
						return false; // Should not succeed
					} catch (error) {
						return true; // Expected to fail
					}
				},
			),
			{ numRuns: 10 }, // Limit runs for performance
		);
	})

Summary: Verifying a JWS token with an incorrect key should fail.


it("should correctly produce different public keys for the different private keys [fuzz]", async () => {
    await fc.assert(
      fc.asyncProperty(fc.bigInt({ min: 1n, max: L - 1n }), async (x: bigint) => {
        const publicKeys = new Map<string, PubKey>();
        const privateKeys: PrivKey[] = [];

        let i = 0n;

        while (x + i * r <= 2n ** 253n) {
          privateKeys.push(new PrivKey(x + i * r));
          i += 1n;
        }

        // eslint-disable-next-line no-restricted-syntax
        for (const privateKey of privateKeys) {
          const publicKey = mulPointEscalar(Base8, BigInt(privateKey.rawPrivKey));

          // eslint-disable-next-line no-await-in-loop
          const witness = await circuit.calculateWitness({
            privKey: BigInt(privateKey.rawPrivKey),
          });
          // eslint-disable-next-line no-await-in-loop
          await circuit.expectConstraintPass(witness);
          // eslint-disable-next-line no-await-in-loop
          const derivedPubkey0 = await getSignal(circuit, witness, "pubKey[0]");
          // eslint-disable-next-line no-await-in-loop
          const derivedPubkey1 = await getSignal(circuit, witness, "pubKey[1]");

          expect(publicKey[0]).to.eq(derivedPubkey0);
          expect(publicKey[1]).to.eq(derivedPubkey1);

          publicKeys.set(privateKey.serialize(), new PubKey([derivedPubkey0, derivedPubkey1]));
        }

        const uniquePublicKeys = [...publicKeys.values()].filter(
          (value, index, array) => array.findIndex((publicKey) => publicKey.equals(value)) === index,
        );

        return uniquePublicKeys.length === privateKeys.length && uniquePublicKeys.length === publicKeys.size;
      }),
      { numRuns: 10_000 },
    );
  })

Summary: Different private keys should produce distinct public keys, ensuring one-to-one correspondence between them.


it("should correctly compute a public key [fuzz]", async () => {
    await fc.assert(
      fc.asyncProperty(fc.bigInt(), async (salt: bigint) => {
        const { pubKey, privKey } = new Keypair(new PrivKey(salt));

        const witness = await circuit.calculateWitness({ privKey: BigInt(privKey.asCircuitInputs()) });
        await circuit.expectConstraintPass(witness);

        const derivedPubkey0 = await getSignal(circuit, witness, "pubKey[0]");
        const derivedPubkey1 = await getSignal(circuit, witness, "pubKey[1]");

        return (
          derivedPubkey0 === pubKey.rawPubKey[0] &&
          derivedPubkey1 === pubKey.rawPubKey[1] &&
          inCurve([derivedPubkey0, derivedPubkey1])
        );
      }),
      { numRuns: 10_000 },
    );
  })

Summary: Computing a public key from a private key should produce expected results where derived public key components match the raw public key components and lie on the elliptic curve.


it("should check the correct value [fuzz]", async () => {
      await fc.assert(
        fc.asyncProperty(
          fc.nat(),
          fc.array(fc.bigInt({ min: 0n, max: r - 1n }), { minLength: leavesPerNode, maxLength: leavesPerNode }),
          async (index: number, elements: bigint[]) => {
            fc.pre(elements.length > index);

            const witness = await circuitQuinSelector.calculateWitness({ index: BigInt(index), in: elements });
            await circuitQuinSelector.expectConstraintPass(witness);
            const out = await getSignal(circuitQuinSelector, witness, "out");

            return out.toString() === elements[index].toString();
          },
        ),
      );
    })

Summary: The circuit outputs the correct element from an array of big integers at a specified index.


it("should loop the value if number is greater that r [fuzz]", async () => {
      await fc.assert(
        fc.asyncProperty(
          fc.nat(),
          fc.array(fc.bigInt({ min: r }), { minLength: leavesPerNode, maxLength: leavesPerNode }),
          async (index: number, elements: bigint[]) => {
            fc.pre(elements.length > index);

            const witness = await circuitQuinSelector.calculateWitness({ index: BigInt(index), in: elements });
            await circuitQuinSelector.expectConstraintPass(witness);
            const out = await getSignal(circuitQuinSelector, witness, "out");

            return out.toString() === (elements[index] % r).toString();
          },
        ),
      );
    })

Summary: Verifies that when an index is selected from an array of big integers, the output is the modulus of the selected element and a specified number \( r \), simulating looping behavior.


it("should throw error if index is out of bounds [fuzz]", async () => {
      await fc.assert(
        fc.asyncProperty(
          fc.nat(),
          fc.array(fc.bigInt({ min: 0n }), { minLength: 1 }),
          async (index: number, elements: bigint[]) => {
            fc.pre(index >= elements.length);

            const circuit = await circomkitInstance.WitnessTester("quinSelector", {
              file: "./trees/incrementalQuinaryTree",
              template: "QuinSelector",
              params: [elements.length],
            });

            return circuit
              .calculateWitness({ index: BigInt(index), in: elements })
              .then(() => false)
              .catch((error: Error) => error.message.includes("Assert Failed"));
          },
        ),
      );
    })

Summary: An error is thrown if the given index is out of bounds when calculating the witness for `quinSelector` with an `IncrementalQuinaryTree`.


it('should always reach its target', () => {
    fc.assert(
      fc.property(SpaceArbitrary, (inputs) => {
        const [space, max_guesses] = inputs;
        knight(space, max_guesses);
        return space.solved();
      }),
    );
  })

Summary: A knight should always reach its target space regardless of the moves attempted, as long as `space.solved()` returns true after invoking the `knight` function.


it("should check value insertion [fuzz]", async () => {
      await fc.assert(
        fc.asyncProperty(
          fc.nat(),
          fc.bigInt({ min: 0n, max: r - 1n }),
          fc.array(fc.bigInt({ min: 0n, max: r - 1n }), { minLength: leavesPerNode - 1, maxLength: leavesPerNode - 1 }),
          async (index: number, leaf: bigint, elements: bigint[]) => {
            fc.pre(index < elements.length);

            const witness = await splicerCircuit.calculateWitness({
              in: elements,
              leaf,
              index: BigInt(index),
            });
            await splicerCircuit.expectConstraintPass(witness);

            const out: bigint[] = [];

            for (let i = 0; i < elements.length + 1; i += 1) {
              // eslint-disable-next-line no-await-in-loop
              const value = await getSignal(splicerCircuit, witness, `out[${i}]`);
              out.push(value);
            }

            return out.toString() === [...elements.slice(0, index), leaf, ...elements.slice(index)].toString();
          },
        ),
      );
    })

Summary: Inserting a value into an array at a specified index should produce an output array matching the expected order.


it("should throw error if index is out of bounds [fuzz]", async () => {
      const maxAllowedIndex = 7;

      await fc.assert(
        fc.asyncProperty(
          fc.integer({ min: maxAllowedIndex + 1 }),
          fc.bigInt({ min: 0n, max: r - 1n }),
          fc.array(fc.bigInt({ min: 0n, max: r - 1n }), { minLength: leavesPerNode - 1, maxLength: leavesPerNode - 1 }),
          async (index: number, leaf: bigint, elements: bigint[]) => {
            fc.pre(index > elements.length);

            return splicerCircuit
              .calculateWitness({
                in: elements,
                leaf,
                index: BigInt(index),
              })
              .then(() => false)
              .catch((error: Error) => error.message.includes("Assert Failed"));
          },
        ),
      );
    })

Summary: An error should be thrown when an index exceeds the allowable bounds in a splicer circuit operation, verifying index-related constraints.


it('should produce an ordered array with respect to a custom compare function', () => {
    fc.assert(
      fc.property(fc.array(fc.integer()), fc.compareBooleanFunc(), (data, compare) => {
        const sorted = sort(data, compare);
        for (let idx = 1; idx < sorted.length; ++idx) {
          // compare(sorted[idx], sorted[idx - 1]):
          // = true : sorted[idx - 1]  > sorted[idx]
          // = false: sorted[idx - 1] <= sorted[idx]
          expect(compare(sorted[idx], sorted[idx - 1])).toBe(false);
          // Meaning of compare:
          // a = b means in terms of ordering a and b are equivalent
          // a < b means in terms of ordering a comes before b
          // One important property is: a < b and b < c implies a < c
        }
      }),
    );
  })

Summary: Sorting a list with a custom compare function should produce an array where no element is greater than the next according to the compare function.


it("should throw error if input is out of bounds [fuzz]", async () => {
      const maxLevel = 1_000n;

      await fc.assert(
        fc.asyncProperty(
          fc.bigInt({ min: 1n, max: maxLevel }),
          fc.bigInt({ min: 1n, max: r - 1n }),
          async (levels: bigint, input: bigint) => {
            fc.pre(BigInt(leavesPerNode) ** levels < input);

            const witness = await circomkitInstance.WitnessTester("quinGeneratePathIndices", {
              file: "./trees/incrementalQuinaryTree",
              template: "QuinGeneratePathIndices",
              params: [levels],
            });

            return witness
              .calculateWitness({ in: input })
              .then(() => false)
              .catch((error: Error) => error.message.includes("Assert Failed"));
          },
        ),
      );
    })

Summary: An error should be thrown when an input is a bigint that exceeds the calculated bounds based on tree levels and node capacity.


it("should check generation of path indices [fuzz]", async () => {
      const maxLevel = 100n;

      await fc.assert(
        fc.asyncProperty(
          fc.bigInt({ min: 1n, max: maxLevel }),
          fc.bigInt({ min: 1n, max: r - 1n }),
          async (levels: bigint, input: bigint) => {
            fc.pre(BigInt(leavesPerNode) ** levels > input);

            const tree = new IncrementalQuinTree(Number(levels), 0n, 5, hash5);

            const circuit = await circomkitInstance.WitnessTester("quinGeneratePathIndices", {
              file: "./trees/incrementalQuinaryTree",
              template: "QuinGeneratePathIndices",
              params: [levels],
            });

            const witness = await circuit.calculateWitness({
              in: input,
            });
            await circuit.expectConstraintPass(witness);

            const values: bigint[] = [];

            for (let i = 0; i < levels; i += 1) {
              // eslint-disable-next-line no-await-in-loop
              const value = await getSignal(circuit, witness, `out[${i}]`);
              tree.insert(value);
              values.push(value);
            }

            const { pathIndices } = tree.genProof(Number(input));

            const isEqual = pathIndices.every((item, index) => item.toString() === values[index].toString());

            return values.length === pathIndices.length && isEqual;
          },
        ),
      );
    })

Summary: Generation of path indices in an incremental quinary tree should accurately match the computed values for given levels and inputs.


it("should check the correct leaf [fuzz]", async () => {
      // TODO: seems js implementation doesn't work with levels more than 22
      const maxLevel = 22;

      await fc.assert(
        fc.asyncProperty(
          fc.integer({ min: 1, max: maxLevel }),
          fc.nat({ max: leavesPerNode - 1 }),
          fc.array(fc.bigInt({ min: 0n, max: r - 1n }), { minLength: leavesPerNode, maxLength: leavesPerNode }),
          async (levels: number, index: number, leaves: bigint[]) => {
            const circuit = await circomkitInstance.WitnessTester("quinLeafExists", {
              file: "./trees/incrementalQuinaryTree",
              template: "QuinLeafExists",
              params: [levels],
            });

            const tree = new IncrementalQuinTree(levels, 0n, leavesPerNode, hash5);
            leaves.forEach((value) => {
              tree.insert(value);
            });

            const proof = tree.genProof(index);

            const witness = await circuit.calculateWitness({
              root: tree.root,
              leaf: leaves[index],
              path_elements: proof.pathElements,
              path_index: proof.pathIndices,
            });

            return circuit
              .expectConstraintPass(witness)
              .then(() => true)
              .catch(() => false);
          },
        ),
      );
    })

Summary: The `IncrementalQuinTree` correctly generates proofs for leaf existence, ensuring the circuit's constraint validation passes with a calculated witness.


it("correctly hashes 2 random values in order", async () => {
        const n = 2;

        circuit = await circomkitInstance.WitnessTester("poseidonHasher", {
          file: "./utils/hashers",
          template: "PoseidonHasher",
          params: [n],
        });

        await fc.assert(
          fc.asyncProperty(
            fc.array(fc.bigInt({ min: 0n, max: r - 1n }), { minLength: n, maxLength: n }),
            async (preImages: bigint[]) => {
              const witness = await circuit.calculateWitness({
                inputs: preImages,
              });
              await circuit.expectConstraintPass(witness);
              const output = await getSignal(circuit, witness, "out");
              const outputJS = hash2(preImages);

              return output === outputJS;
            },
          ),
        );
      })

Summary: The test verifies that hashing two random big integer values using the `PoseidonHasher` circuit produces the same output as the `hash2` function.


it("correctly hashes 3 random values", async () => {
        const n = 3;

        circuit = await circomkitInstance.WitnessTester("poseidonHasher", {
          file: "./utils/hashers",
          template: "PoseidonHasher",
          params: [n],
        });

        await fc.assert(
          fc.asyncProperty(
            fc.array(fc.bigInt({ min: 0n, max: r - 1n }), { minLength: n, maxLength: n }),
            async (preImages: bigint[]) => {
              const witness = await circuit.calculateWitness({
                inputs: preImages,
              });
              await circuit.expectConstraintPass(witness);
              const output = await getSignal(circuit, witness, "out");
              const outputJS = hash3(preImages);

              return output === outputJS;
            },
          ),
        );
      })

Summary: Hashes of three random values should match the expected output using the `PoseidonHasher` circuit and the `hash3` function.


it("correctly hashes 4 random values", async () => {
        const n = 4;

        circuit = await circomkitInstance.WitnessTester("poseidonHasher", {
          file: "./utils/hashers",
          template: "PoseidonHasher",
          params: [n],
        });

        await fc.assert(
          fc.asyncProperty(
            fc.array(fc.bigInt({ min: 0n, max: r - 1n }), { minLength: n, maxLength: n }),
            async (preImages: bigint[]) => {
              const witness = await circuit.calculateWitness({
                inputs: preImages,
              });
              await circuit.expectConstraintPass(witness);
              const output = await getSignal(circuit, witness, "out");
              const outputJS = hash4(preImages);

              return output === outputJS;
            },
          ),
        );
      })

Summary: The function correctly hashes four random bigint values using both a circuit and a JavaScript function, comparing outputs to ensure they match.


it("should correctly hash a message [fuzz]", async () => {
      const random50bitBigInt = (salt: bigint): bigint =>
        // eslint-disable-next-line no-bitwise
        ((BigInt(1) << BigInt(50)) - BigInt(1)) & salt;

      await fc.assert(
        fc.asyncProperty(
          fc.bigInt({ min: 0n }),
          fc.bigInt({ min: 0n }),
          fc.bigInt({ min: 0n }),
          fc.bigInt({ min: 0n }),
          fc.bigInt({ min: 0n }),
          fc.bigInt({ min: 0n }),
          async (
            stateIndex: bigint,
            voteOptionIndex: bigint,
            newVoteWeight: bigint,
            nonce: bigint,
            pollId: bigint,
            salt: bigint,
          ) => {
            const { pubKey, privKey } = new Keypair();

            const command: PCommand = new PCommand(
              random50bitBigInt(stateIndex),
              pubKey,
              random50bitBigInt(voteOptionIndex),
              random50bitBigInt(newVoteWeight),
              random50bitBigInt(nonce),
              random50bitBigInt(pollId),
              salt,
            );

            const ecdhSharedKey = Keypair.genEcdhSharedKey(privKey, pubKey);
            const signature = command.sign(privKey);
            const message = command.encrypt(signature, ecdhSharedKey);
            const messageHash = message.hash(pubKey);
            const circuitInputs = {
              in: message.asCircuitInputs(),
              encPubKey: pubKey.asCircuitInputs() as unknown as [bigint, bigint],
            };
            const witness = await circuit.calculateWitness(circuitInputs);
            await circuit.expectConstraintPass(witness);
            const output = await getSignal(circuit, witness, "hash");

            return output === messageHash;
          },
        ),
      );
    })

Summary: Hashes of encrypted and signed messages should match the computed circuit output for various randomly generated inputs.


test('autodetectDoubleEncoded_fastcheck', () => {
  fc.assert(
    fc.property(fc.string({ minLength: 1, size: 'medium', unit: 'grapheme' }), (data) => {
      const asciiOnly = [...data].every((c) => (c.codePointAt(0) ?? -1) < 128)
      expect(doubleEncodedUTF8(e(data))).toBe(false)
      expect(doubleEncodedUTF8(de(data))).toBe(!asciiOnly)
    }),
  )
})

Summary: `doubleEncodedUTF8` should return false for normally encoded UTF-8 strings and true for double-encoded ones when the string includes non-ASCII characters.


it('should produce an array such that the product equals the input', () => {
    fc.assert(
      fc.property(fc.nat(MAX_INPUT), (n) => {
        const factors = decompPrime(n);
        const productOfFactors = factors.reduce((a, b) => a * b, 1);
        return productOfFactors === n;
      }),
    );
  })

Summary: The array produced by `decompPrime` should have a product that equals the input number.


it(`should parse AstExpression`, () => {
        fc.assert(
            fc.property(randomAstExpression(maxDepth), (generatedAst) => {
                const prettyBefore = prettyPrint(generatedAst);

                const parsedAst = parser.parseExpression(prettyBefore);
                const prettyAfter = prettyPrint(parsedAst);

                expect(prettyBefore).toBe(prettyAfter);
                const actual = eqExpressions(generatedAst, parsedAst);
                if (!actual) {
                    diffAstObjects(
                        generatedAst,
                        parsedAst,
                        prettyBefore,
                        prettyAfter,
                    );
                }
                expect(actual).toBe(true);
            }),
            { seed: 1, numRuns: 5000 },
        );
    })

Summary: Parsing and re-serializing an `AstExpression` should yield identical pretty-printed strings, and the original and parsed expressions should be equivalent.


it("should not extend or reduce the duration of tasks", () => {
  fc.assert(
    fc.property(tasksArbitrary(), (tasks) => {
      // Arrange / Act
      const schedule = christmasFactorySchedule(tasks);

      // Assert
      for (const scheduledTask of schedule) {
        const task = tasks.find((t) => t.taskId === scheduledTask.taskId);
        expect(scheduledTask.finish - scheduledTask.start).toBe(
          task.estimatedTime
        );
      }
    })
  );
})

Summary: `christmasFactorySchedule` should schedule tasks such that the duration between the start and finish times equals the task's estimated time.


it("should start tasks as soon as possible", () => {
  fc.assert(
    fc.property(tasksArbitrary(), (tasks) => {
      // Arrange / Act
      const schedule = christmasFactorySchedule(tasks);

      // Assert
      for (const scheduledTask of schedule) {
        const dependencies = tasks.find(
          (t) => t.taskId === scheduledTask.taskId
        )!.dependsOnTasks;
        const finishTimeDependencies = dependencies.map((depTaskId) => {
          const depScheduledTask = schedule.find((s) => s.taskId === depTaskId);
          return depScheduledTask.finish;
        });
        const expectedStart =
          finishTimeDependencies.length !== 0
            ? Math.max(...finishTimeDependencies)
            : 0;
        expect(scheduledTask.start).toBe(expectedStart);
      }
    })
  );
})

Summary: Tasks should be scheduled to start immediately after all their dependencies are completed.


it("should be able to rebuild previous year given only the diff", () => {
  fc.assert(
    fc.property(
      wishListArbitrary(),
      wishListArbitrary(),
      (previousYear, currentYear) => {
        // Arrange / Act
        const computedDiff = wishListsDiffer(previousYear, currentYear);

        // Assert
        expect(previousYearFromDiff(computedDiff)).toEqual(previousYear);
      }
    )
  );
})

Summary: Rebuilding the previous year from a diff should yield the original previous year text.


it("should be able to rebuild current year given only the diff", () => {
  fc.assert(
    fc.property(
      wishListArbitrary(),
      wishListArbitrary(),
      (previousYear, currentYear) => {
        // Arrange / Act
        const computedDiff = wishListsDiffer(previousYear, currentYear);

        // Assert
        expect(currentYearFromDiff(computedDiff)).toEqual(currentYear);
      }
    )
  );
})

Summary: The property should hold that reconstructing the current year's wishlist from the computed diff between two wishlists results in an exact match to the original current year.


it("should compute the diff having the maximal number of unchanged lines", () => {
  fc.assert(
    fc.property(diffArbitrary(), (diff) => {
      // Arrange
      const previousYear = previousYearFromDiff(diff);
      const currentYear = currentYearFromDiff(diff);

      // Act
      const computedDiff = wishListsDiffer(previousYear, currentYear);

      // Assert
      expect(countUnchangedLines(computedDiff)).toBeGreaterThanOrEqual(
        countUnchangedLines(diff)
      );
    })
  );
})

diffArbitrary previousYearFromDiff currentYearFromDiff countUnchangedLines

Summary: The computed diff from `wishListsDiffer` should have at least as many unchanged lines as the original diff input.


it("should select some elves whenever there is a solution with one elf", () => {
  fc.assert(
    fc.property(
      fc.array(fc.integer({ min: 1 }), { minLength: 1 }),
      fc.nat(),
      (elves, modElf1) => {
        // Arrange
        const indexElf1 = modElf1 % elves.length;
        const wallHeight = elves[indexElf1];

        // Act
        const selectedElves = spyOnSanta(elves, wallHeight);

        // Assert
        expect(selectedElves).not.toBe(undefined);
        assertElves(elves, selectedElves!, wallHeight);
      }
    )
  );
})

Summary: Selecting elves correctly matches the wall height using a single elf, while ensuring valid indices, no repetitions, and a selection size between 1 and 3.


it("should select some elves whenever there is a solution with two elves", () => {
  fc.assert(
    fc.property(
      fc.array(fc.integer({ min: 1 }), { minLength: 2 }),
      fc.nat(),
      fc.nat(),
      (elves, modElf1, modElf2) => {
        // Arrange
        const indexElf1 = modElf1 % elves.length;
        const indexElf2 = modElf2 % elves.length;
        fc.pre(indexElf1 !== indexElf2);
        const wallHeight = elves[indexElf1] + elves[indexElf2];

        // Act
        const selectedElves = spyOnSanta(elves, wallHeight);

        // Assert
        expect(selectedElves).not.toBe(undefined);
        assertElves(elves, selectedElves!, wallHeight);
      }
    )
  );
})

Summary: The test checks that when there is a solution involving the selection of two distinct elves to reach a specified wall height, `spyOnSanta` successfully selects elves whose combined heights exactly match the wall height, meeting specified constraints.


it("should select some elves whenever there is a solution with three elves", () => {
  fc.assert(
    fc.property(
      fc.array(fc.integer({ min: 1 }), { minLength: 3 }),
      fc.nat(),
      fc.nat(),
      fc.nat(),
      (elves, modElf1, modElf2, modElf3) => {
        // Arrange
        const indexElf1 = modElf1 % elves.length;
        const indexElf2 = modElf2 % elves.length;
        const indexElf3 = modElf3 % elves.length;
        fc.pre(indexElf1 !== indexElf2);
        fc.pre(indexElf1 !== indexElf3);
        fc.pre(indexElf2 !== indexElf3);
        const wallHeight =
          elves[indexElf1] + elves[indexElf2] + elves[indexElf3];

        // Act
        const selectedElves = spyOnSanta(elves, wallHeight);

        // Assert
        expect(selectedElves).not.toBe(undefined);
        assertElves(elves, selectedElves!, wallHeight);
      }
    )
  );
})

Summary: Whenever there is a solution with three distinct elves that match the wall height, `spyOnSanta` correctly selects between 1 and 3 elves whose combined height equals the wall height without repetition and using valid indexes.


it("should either propose a valid solution or nothing", () => {
  fc.assert(
    fc.property(
      fc.array(fc.integer({ min: 1 })),
      fc.nat(),
      (elves, wallHeight) => {
        // Arrange / Act
        const selectedElves = spyOnSanta(elves, wallHeight);

        // Assert
        if (selectedElves !== undefined) {
          assertElves(elves, selectedElves!, wallHeight);
        }
      }
    )
  );
})

Summary: The function `spyOnSanta` should return a valid selection of 1 to 3 elves whose total height matches the wall height or return nothing.


it("should find a place whenever the map has at least one with the right size", () => {
  fc.assert(
    fc.property(
      fc
        .record({
          // Size of the map
          mapWidth: fc.nat({ max: 100 }),
          mapHeight: fc.nat({ max: 100 }),
        })
        .chain((mapSize) =>
          fc.record({
            // Default map with some holes for available places
            rawMap: mapArbitrary(mapSize),
            // Stand that will be allocated for Santa
            // We will free this room so that it will be available
            request: rectAreaArbitrary(mapSize),
          })
        ),
      ({ rawMap, request }) => {
        // Arrange
        // Allocate some room to Santa so that he will be able
        // to have his stand on the market
        const map: boolean[][] = [];
        for (let y = 0; y !== rawMap.length; ++y) {
          map[y] = [];
          for (let x = 0; x !== rawMap[0].length; ++x) {
            map[y][x] =
              rawMap[y][x] ||
              (request.x.start <= x &&
                x < request.x.end &&
                request.y.start <= y &&
                y < request.y.end);
          }
        }
        const requestedArea = {
          width: request.x.end - request.x.start,
          height: request.y.end - request.y.start,
        };

        // Act
        const foundPlace = findPlaceForSanta(map, requestedArea);

        // Assert
        expect(foundPlace).not.toBe(undefined);
      }
    )
  );
})

Summary: `findPlaceForSanta` should successfully find an available place for Santa when at least one area of the requested size exists on the map.


it("should either return no place or the start of valid place with enough room", () => {
  fc.assert(
    fc.property(
      fc
        .record({
          // Size of the map
          mapWidth: fc.nat({ max: 100 }),
          mapHeight: fc.nat({ max: 100 }),
        })
        .chain((mapSize) =>
          fc.record({
            // Default map with some holes for available places
            map: mapArbitrary(mapSize),
            // Size of the stand requested by Santa
            requestedArea: fc.record({
              width: fc.integer({ min: 0, max: mapSize.mapWidth }),
              height: fc.integer({ min: 0, max: mapSize.mapHeight }),
            }),
          })
        ),
      ({ map, requestedArea }) => {
        // Arrange / Act
        const foundPlace = findPlaceForSanta(map, requestedArea);

        // Assert
        if (foundPlace !== undefined) {
          for (let dy = 0; dy !== requestedArea.height; ++dy) {
            for (let dx = 0; dx !== requestedArea.width; ++dx) {
              expect(map[foundPlace.y + dy][foundPlace.x + dx]).toBe(true);
            }
          }
        }
      }
    )
  );
})

Summary: `findPlaceForSanta` returns either no place or the starting position of a valid area in the map with enough room matching the requested dimensions.


it("should build a linear trunk", () => {
  fc.assert(
    fc.property(fc.integer({ min: 1, max: 1000 }), (n) => {
      // Arrange / Act
      const tree = drawTree(n);

      // Assert
      // Remove all the leaves from the tree to only keep the trunk
      const treeWithoutLeaves = tree
        .split("\n")
        .map((level) => level.replace(/[()]/g, " ").trimRight());
      for (const level of treeWithoutLeaves) {
        expect(level.trimLeft()).toEqual("^");
        expect(level).toEqual(treeWithoutLeaves[0]);
      }
    })
  );
})

Summary: A tree generated by `drawTree` with any integer input from 1 to 1000 should produce a linear trunk consisting of a single repeated character "^" across all levels without leaves.


it("should offset leaves from one level to the next one", () => {
  fc.assert(
    fc.property(fc.integer({ min: 1, max: 1000 }), (n) => {
      // Arrange / Act
      const tree = drawTree(n);

      // Assert
      const treeLevels = tree.split("\n").map((level) => level.trim());
      for (let index = 1; index < n; ++index) {
        expect(treeLevels[index]).toEqual("(" + treeLevels[index - 1] + ")");
      }
    })
  );
})

Summary: The test verifies that each level of a tree is correctly offset by enclosing the previous level in parentheses.


it("should create a base of size two with levels identical to the top", () => {
  fc.assert(
    fc.property(fc.integer({ min: 1, max: 1000 }), (n) => {
      // Arrange / Act
      const tree = drawTree(n);

      // Assert
      const treeLevels = tree.split("\n");
      expect(treeLevels).toHaveLength(n + 2);
      expect(treeLevels[n]).toEqual(treeLevels[0]);
      expect(treeLevels[n + 1]).toEqual(treeLevels[0]);
    })
  );
})

Summary: The tree should have `n + 2` levels, with the first, last, and `n-th` levels being identical.


it("should build a path starting by the requested departure whenever a path from start to end exists", () => {
  fc.assert(
    fc.property(orientedGraphArbitrary(), ({ knownPath, tracks }) => {
      // Arrange
      const departure = knownPath[0];
      const destination = knownPath[knownPath.length - 1];

      // Act
      const shortestPath = metroRoute(departure, destination, tracks);

      // Assert
      if (departure === destination) expect(shortestPath).toEqual([]);
      else expect(shortestPath![0].from).toBe(departure);
    })
  );
})

Summary: The presence of a path from start to end in a graph ensures that `metroRoute` builds a path starting with the requested departure node.


it("should build a path ending by the requested destination whenever a path from start to end exists", () => {
  fc.assert(
    fc.property(orientedGraphArbitrary(), ({ knownPath, tracks }) => {
      // Arrange
      const departure = knownPath[0];
      const destination = knownPath[knownPath.length - 1];

      // Act
      const shortestPath = metroRoute(departure, destination, tracks);

      // Assert
      if (departure === destination) expect(shortestPath).toEqual([]);
      else expect(shortestPath![shortestPath!.length - 1].to).toBe(destination);
    })
  );
})

Summary: The function `metroRoute` produces a path ending at the specified destination if a path from start to end exists in the given tracks.


it("should build an ordered path of tracks whenever a path from start to end exists", () => {
  fc.assert(
    fc.property(orientedGraphArbitrary(), ({ knownPath, tracks }) => {
      // Arrange
      const departure = knownPath[0];
      const destination = knownPath[knownPath.length - 1];

      // Act
      const shortestPath = metroRoute(departure, destination, tracks);

      // Assert
      for (let index = 1; index < shortestPath!.length; ++index) {
        expect(shortestPath![index].from).toBe(shortestPath![index - 1].to);
      }
    })
  );
})

Summary: Given an oriented graph with a known path from start to end, the `metroRoute` function should construct a valid ordered path of tracks with correct connections between nodes.


it("should build a path of tracks being a subset of the tracks of the graph whenever a path from start to end exists", () => {
  fc.assert(
    fc.property(orientedGraphArbitrary(), ({ knownPath, tracks }) => {
      // Arrange
      const departure = knownPath[0];
      const destination = knownPath[knownPath.length - 1];

      // Act
      const shortestPath = metroRoute(departure, destination, tracks);

      // Assert
      for (const edge of shortestPath!) {
        expect(shortestPath).toContainEqual(edge);
      }
    })
  );
})

Summary: The test ensures that the `metroRoute` function can find a valid path from start to end, with the path being a subset of the provided graph tracks when such a path exists.


it("should be able to find a path shorther or equal to the one we come up with", () => {
  fc.assert(
    fc.property(
      orientedGraphArbitrary(),
      ({ knownPath, knownPathTracks, tracks }) => {
        // Arrange
        const departure = knownPath[0];
        const destination = knownPath[knownPath.length - 1];

        // Act
        const shortestPath = metroRoute(departure, destination, tracks);

        // Assert
        const distanceKnownPath = knownPathTracks.reduce(
          (acc, e) => acc + e.length,
          0
        );
        const distanceShortestPath = shortestPath!.reduce(
          (acc, e) => acc + e.length,
          0
        );
        expect(distanceShortestPath).toBeLessThanOrEqual(distanceKnownPath);
      }
    )
  );
})

Summary: The function `metroRoute` should find a path between departure and destination with a distance less than or equal to a precomputed known path in the graph.


it("should not return any path whenever there is no way going from start to end", () => {
  fc.assert(
    fc.property(
      orientedGraphNoWayArbitrary(),
      ({ departure, destination, tracks }) => {
        // Arrange / Act
        const shortestPath = metroRoute(departure, destination, tracks);

        // Assert
        expect(shortestPath).toBe(undefined);
      }
    )
  );
})

Summary: Whenever no path exists from the start node (0) to the end node (19) in a graph, the `metroRoute` function should return `undefined`.


it("should detect any valid palindrome having even number of characters", () => {
  fc.assert(
    fc.property(fc.fullUnicodeString(), (start) => {
      // Arrange
      const reversedStart = [...start].reverse().join("");
      const palindrome = `${start}${reversedStart}`;

      // Act / Assert
      expect(isPalindrome(palindrome)).toBe(true);
    })
  );
})

Summary: A valid palindrome with an even number of characters is correctly detected by `isPalindrome`.


it("should detect any invalid palindrome", () => {
  fc.assert(
    fc.property(
      fc.fullUnicodeString(),
      fc.fullUnicode(),
      fc.fullUnicode(),
      fc.fullUnicodeString(),
      (start, a, b, middle) => {
        // Arrange
        fc.pre(a !== b);
        const reversedStart = [...start].reverse().join("");
        const notPalindrome = `${start}${a}${middle}${b}${reversedStart}`;
        // not a palindrome as the mirror of a is b and a !== b

        // Act / Assert
        expect(isPalindrome(notPalindrome)).toBe(false);
      }
    )
  );
})

Summary: A string constructed with distinct characters in mirrored positions should not be identified as a palindrome.


it("should be equivalent to non-optimal implementation based on fully reversing the string", () => {
  fc.assert(
    fc.property(fc.fullUnicodeString(), (s) => {
      // Arrange
      const reversedS = [...s].reverse().join("");
      const expectedResult = reversedS === s;

      // Act / Assert
      expect(isPalindrome(s)).toBe(expectedResult);
    })
  );
})

Summary: The function `isPalindrome` should return true if and only if reversing the full Unicode string results in the same string.


it("should consider any composite with one prime factor >7 as non-humble", () => {
  fc.assert(
    fc.property(
      fc
        .integer({ min: 11 }) // 8,9,10 would be filtered
        .filter((v) => v % 2 !== 0)
        .filter((v) => v % 3 !== 0)
        .filter((v) => v % 5 !== 0)
        .filter((v) => v % 7 !== 0),
      fc.array(fc.integer({ min: 1, max: 195225786 })),
      (tooLarge, factors) => {
        // Arrange
        let n = tooLarge;
        for (const f of factors) {
          if (n * f > 2 ** 31 - 1) break;
          n = n * f;
        }

        // Act / Assert
        expect(isHumbleNumber(n)).toBe(false);
      }
    )
  );
})

Summary: Numbers with a prime factor greater than 7 should not be identified as humble numbers.


it("should produce an array having the same length", () => {
  fc.assert(
    fc.property(fc.array(fc.anything()), (data) => {
      // Arrange / Act
      const rev = reversed(data);

      // Assert
      expect(rev).toHaveLength(data.length);
    })
  );
})

Summary: The `reversed` function should produce an array with the same length as the input array.


it("should reverse any array", () => {
  fc.assert(
    fc.property(fc.array(fc.anything()), (data) => {
      // Arrange / Act
      const rev = reversed(data);

      // Assert
      for (let index = 0; index !== data.length; ++index) {
        expect(rev[rev.length - index - 1]).toBe(data[index]);
      }
    })
  );
})

Summary: Reversing any array should produce an output where the elements are in reverse order compared to the input.


it("should properly reverse concatenated arrays: rev concat(a,b) = concat(rev b, rev a)", () => {
  fc.assert(
    fc.property(fc.array(fc.anything()), fc.array(fc.anything()), (a, b) => {
      // Arrange / Act
      const rev = reversed([...a, ...b]);
      const revA = reversed(a);
      const revB = reversed(b);

      // Assert
      expect(rev).toEqual([...revB, ...revA]);
    })
  );
})

Summary: Reversing concatenated arrays should yield the concatenation of the reversed arrays in reverse order.


it("should go back to the original array if reversed twice", () => {
  fc.assert(
    fc.property(fc.array(fc.anything()), (data) => {
      // Arrange / Act / Assert
      expect(reversed(reversed(data))).toEqual(data);
    })
  );
})

Summary: Reversing an array twice should return the original array.


it("should predict the right podium", () => {
  fc.assert(
    fc.property(
      fc.array(fc.nat(), { minLength: 25, maxLength: 25 }),
      (speeds) => {
        // Arrange
        const compareParticipants = (pa: number, pb: number) => {
          if (speeds[pa] !== speeds[pb]) return speeds[pb] - speeds[pa];
          else return pa - pb;
        };
        const runRace = (
          ...participants: RaceParticipants
        ): RaceParticipants => {
          return participants.sort(compareParticipants);
        };

        // Act
        const podium = racePodium(runRace);

        // Assert
        const rankedParticipants = [...Array(25)]
          .map((_, i) => i)
          .sort(compareParticipants);
        const expectedPodium = rankedParticipants.slice(0, 3);
        expect(podium).toEqual(expectedPodium);
      }
    )
  );
})

Summary: `racePodium` correctly predicts the top three participants based on sorted speeds of 25 participants.


it("should never do more than 7 races", () => {
  fc.assert(
    fc.property(
      fc.array(fc.nat(), { minLength: 25, maxLength: 25 }),
      (speeds) => {
        // Arrange
        const compareParticipants = (pa: number, pb: number) => {
          if (speeds[pa] !== speeds[pb]) return speeds[pb] - speeds[pa];
          else return pa - pb;
        };
        const runRace = jest.fn(
          (...participants: RaceParticipants): RaceParticipants => {
            return participants.sort(compareParticipants);
          }
        );

        // Act
        racePodium(runRace);

        // Assert
        expect(runRace.mock.calls.length).toBeLessThanOrEqual(7);
      }
    )
  );
})

Summary: `racePodium` should require at most 7 races for determining the order of participants based on their speeds.


it("should group selected tabs together", () => {
  fc.assert(
    fc.property(
      tabsWithSelectionArb(),
      ({ tabs, selectedTabs, movePosition }) => {
        // Arrange / Act
        const newTabs = reorderTabs(tabs, selectedTabs, movePosition);

        // Assert
        const startMovedSelection = newTabs.indexOf(selectedTabs[0]);
        expect(
          newTabs.slice(
            startMovedSelection,
            startMovedSelection + selectedTabs.length
          )
        ).toEqual(selectedTabs);
      }
    )
  );
})

Summary: Selected tabs should be grouped together in the reordered tabs list.


it("should insert all the selected tabs before the move position", () => {
  fc.assert(
    fc.property(
      tabsWithSelectionArb(),
      ({ tabs, selectedTabs, movePosition }) => {
        // Arrange / Act
        const newTabs = reorderTabs(tabs, selectedTabs, movePosition);

        // Assert
        const movePositionIndex = newTabs.indexOf(movePosition);
        for (const selected of selectedTabs) {
          const selectedIndex = newTabs.indexOf(selected);
          expect(selectedIndex).toBeLessThan(movePositionIndex);
        }
      }
    )
  );
})

Summary: Reordering tabs should insert all selected tabs before the specified move position.


it("should not alter non-selected tabs", () => {
  fc.assert(
    fc.property(
      tabsWithSelectionArb(),
      ({ tabs, selectedTabs, movePosition }) => {
        // Arrange / Act
        const newTabs = reorderTabs(tabs, selectedTabs, movePosition);

        // Assert
        expect(newTabs.filter((t) => !selectedTabs.includes(t))).toEqual(
          tabs.filter((t) => !selectedTabs.includes(t))
        );
      }
    )
  );
})

Summary: Reordering tabs should not change the order of non-selected tabs.


it("should not change the list of tabs, just its order", () => {
  fc.assert(
    fc.property(
      tabsWithSelectionArb(),
      ({ tabs, selectedTabs, movePosition }) => {
        // Arrange / Act
        const newTabs = reorderTabs(tabs, selectedTabs, movePosition);

        // Assert
        expect([...newTabs].sort()).toEqual([...tabs].sort());
      }
    )
  );
})

Summary: Reordering tabs should not change the original set of tabs, only their order.


it("should accept any well-parenthesized expression", () => {
  fc.assert(
    fc.property(wellParenthesizedStringArbitrary, (expression) => {
      expect(validParentheses(expression)).toBe(true);
    })
  );
})

Summary: The property should hold that `validParentheses` returns true for any well-parenthesized expression.


it("should reject any expression not containing an even number of signs", () => {
  fc.assert(
    fc.property(
      fc
        .tuple(
          fc.array(
            fc.tuple(
              fc.constantFrom("(", "[", "{", ")", "]", "}"),
              fc.constantFrom("(", "[", "{", ")", "]", "}")
            )
          ),
          fc.constantFrom("(", "[", "{", ")", "]", "}")
        )
        .chain(([evenNumParentheses, extraParenthesis]) => {
          const parentheses = [...evenNumParentheses.flat(), extraParenthesis];
          return fc
            .shuffledSubarray(parentheses, { minLength: parentheses.length })
            .map((parentheses) => parentheses.join(""));
        }),
      (invalidExpression) => {
        expect(validParentheses(invalidExpression)).toBe(false);
      }
    )
  );
})

Summary: Expressions not containing an even number of parentheses characters should be rejected by `validParentheses`.